Reputation: 33213
I have a string in json format and I want to extract certain values from that json. For example:
{"foo":"this is foo", "bar":{"nested_bar": "this is nested bar"} }
A user might want to print either foo
or bar
or both.
Right now, I have a simple class which can read only flat json.
How do I modify the following code to incorporate nested json?
Another question is what is a good way to represent the tags which I want to extract as in flat json? I was passing an array.
public class JsonParser {
public static String[] tagsToExtract;
public JsonParser(String[] tags){
tagsToExtract = tags;
}
public HashMap<String, Object> extractInformation(Text line) throws JSONException{
HashMap<String, Object> outputHash = new HashMap<String, Object>();
JSONObject jsn = new JSONObject(line.toString());
for (int i =0; i < tagsToExtract.length; i++){
outputHash.put(tagsToExtract[i],jsn.get(tagsToExtract[i].toString()));
}
return outputHash;
}
}
Upvotes: 0
Views: 1988
Reputation: 3931
There are quite a few JSON libraries for Java that will do exactly what you want. A couple of the more highly regarded ones are:
And you can find a more in-depth discussion of the various options here: https://stackoverflow.com/questions/338586/a-better-java-json-library
If you are really interested in writing your own parser for it, though, the hint I will give is to take advantage of recursion. Suppose you have a JSON object something like this:
{
prop1: (some value),
prop2: (some value),
...
}
Notice that when you start parsing the top-level object, you're doing exactly the same thing as you will be doing when you parse each value - because the values themselves can be just another JSON object. So a simple way to get started would be to write a parser which just gets the keys and their associated values as strings, without processing the values. Then, call the same algorithm again on each value - and so on, until you get to a value that is just a plain value - a string, a number, etc.
Upvotes: 1