I am trying to parse JSON strings in Java and find the key-value pairs so that I can determine the approximate structure of the JSON object since object structure of JSON string is unknown.
For example, one execution may have a JSON string like this:
{"id" : 12345, "days" : [ "Monday", "Wednesday" ], "person" : { "firstName" : "David", "lastName" : "Menoyo" } }
And another like this:
{"url" : "http://someurl.com", "method" : "POST", "isauth" : false }
How would I cycle through the various JSON elements and determine the keys and their values? I looked at jackson-core
's JsonParser
. I see how I can grab the next "token" and determine what type of token it is (i.e., field name, value, array start, etc), but, I don't know how to grab the actual token's value.
For example:
public void parse(String json) { try { JsonFactory f = new JsonFactory(); JsonParser parser = f.createParser(json); JsonToken token = parser.nextToken(); while (token != null) { if (token.equals(JsonToken.START_ARRAY)) { logger.debug("Start Array : " + token.toString()); } else if (token.equals(JsonToken.END_ARRAY)) { logger.debug("End Array : " + token.toString()); } else if (token.equals(JsonToken.START_OBJECT)) { logger.debug("Start Object : " + token.toString()); } else if (token.equals(JsonToken.END_OBJECT)) { logger.debug("End Object : " + token.toString()); } else if (token.equals(JsonToken.FIELD_NAME)) { logger.debug("Field Name : " + token.toString()); } else if (token.equals(JsonToken.VALUE_FALSE)) { logger.debug("Value False : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NULL)) { logger.debug("Value Null : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_FLOAT)) { logger.debug("Value Number Float : " + token.toString()); } else if (token.equals(JsonToken.VALUE_NUMBER_INT)) { logger.debug("Value Number Int : " + token.toString()); } else if (token.equals(JsonToken.VALUE_STRING)) { logger.debug("Value String : " + token.toString()); } else if (token.equals(JsonToken.VALUE_TRUE)) { logger.debug("Value True : " + token.toString()); } else { logger.debug("Something else : " + token.toString()); } token = parser.nextToken(); } } catch (Exception e) { logger.error("", e); } }
Is there a class in jackson
or some other library (gson
or simple-json
) that produces a tree, or allows one to cycle through the json elements and obtain the actual key names in addition to the values?
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.
json above, that file actually contains text in the form of a JSON object or array, which happens to look like JavaScript. Just like with text files, if you want to use JSON in your project, you'll need to parse or change it into something your programming language can understand.
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()); } }
If a different library is fine for you, you could try org.json:
JSONObject object = new JSONObject(myJSONString); String[] keys = JSONObject.getNames(object); for (String key : keys) { Object value = object.get(key); // Determine type of value and do something with it... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With