0

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;

}

}
2
  • 5
    Have you considered using a JSON parsing library such as, for instance, Jackson? Commented May 31, 2013 at 18:18
  • 2
    Yes, if you go to json.org it lists about a dozen JSON parsers for Java. Commented May 31, 2013 at 18:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.