Parsing JSON in Java without knowing JSON format
Take a look at Jacksons built-in tree model feature.
And your code will be:
public void parse(String json) {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
Parse json without knowning the keys
This is Just an Example.
For a JSON Like
{
"status": "OK",
"search_result": [
{
"product": "abc",
"id": "1132",
"question_mark": {
"141": {
"count": "141",
"more_description": "this is abc",
"seq": "2"
},
"8911": {
"count": "8911",
"more_desc": "this is cup",
"seq": "1"
}
},
"name": "some name",
"description": "This is some product"
},
{
"product": "XYZ",
"id": "1129",
"question_mark": {
"379": {
"count": "379",
"more_desc": "this is xyz",
"seq": "5"
},
"845": {
"count": "845",
"more_desc": "this is table",
"seq": "6"
},
"12383": {
"count": "12383",
"more_desc": "Jumbo",
"seq": "4"
},
"257258": {
"count": "257258",
"more_desc": "large",
"seq": "1"
}
},
"name": "some other name",
"description": "this is some other product"
}
]
}
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Try this Code Too
public void parse(String json) {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key:"field.getKey() + "\tValue:" + field.getValue());
}
}
also give a look at this link
https://github.com/alibaba/fastjson
Parsing JSON in Java without knowing JSON format (like with selectToken)
Well, finally after doing some more research I found this:
https://github.com/json-path/JsonPath
That's exactly what I needed, as it lets you access a JSON Object and finding a token with its path, exactly as I did with NewtonSoft.Json in .NET.
I think it's really interesting, as no matter what the structure of the JSON file is, you can find a value by giving only the path with the format "$..path".
Parse JSON without knowing format (can be one of two different objects)
Personally, I would parse the JSON using GSON or something similar and look for the key that is unique to one of the JSON formats, for instance "age". In reality, you could probably do this as a String as @user743414 mentioned as well.
UPDATE:
Here is some code to reflect what I'm talking about
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
if(keys.contains("age")){
//Map to one object
} else {
//Map to the other object
}
JSON parsing without using Java objects
The official docs for Jackson mention 3 different ways to parse a JSON doc from Java. The first 2 do not require "Java object matching the JSON structure". In Summary :
- Streaming API (aka "Incremental parsing/generation") reads and writes JSON content as discrete events.
- Tree Model provides a mutable in-memory tree representation of a JSON document. ObjectMapper can build trees that consist of JsonNode nodes.
- Data Binding converts JSON to and from POJOs based either on property accessor conventions or annotations.
- With simple data binding you convert to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls
- With full data binding you convert to and from any Java bean type (as well as "simple" types mentioned above)
Another option is to generate Java Beans from JSON documents. You mileage may vary and you may/probably will have to modify the generated files. There are at least 5 online tools for that purpose that you can try:
- http://www.jsonschema2pojo.org/
- http://pojo.sodhanalibrary.com/
- https://timboudreau.com/blog/json/read
- http://jsongen.byingtondesign.com/
- http://json2java.azurewebsites.net/
There are also IDE plugins that you can use. For instance this one for Intellij https://plugins.jetbrains.com/idea/plugin/7678-jackson-generator-plugin
How can I parse JSONObject without knowing the name?
String json="" // place your json format here in double Quotes with proper escapes .......
jObject = new JSONObject(json.trim());
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
// do what ever you want with the JSONObject.....
}
}
Related Topics
Finding the Second Highest Number in Array
What Is the Purpose of @Namedarg Annotation in Javafx 8
How to Compile & Run Java Program in Another Java Program
Get MAC Address on Local MAChine with Java
Java 8: Difference Between Method Reference Bound Receiver and Unbound Receiver
Java Streams: Replacing Groupingby and Reducing by Tomap
How to Use .Jar Files in Netbeans
Swing's Keylistener and Multiple Keys Pressed at the Same Time
Dynamic Graphics Object Painting
Populating Spring @Value During Unit Test
Can a Constructor in Java Be Private
Retrieve Version from Maven Pom.Xml in Code
Convert from List<Completablefuture> to Completablefuture<List>