0

I just wanted to ask, how to simply parse nested JSON structure in Java that looks like this:

{
   "goods":{
      "NY Store":[
         {
            "product":"Teddybear",
            "available":"20"
         },
         {
            "product":"Mountain bike",
            "available":"0"
         }]
      "LA Store":[
         {
            "product": ....and so on

I want to get all the products from all the stores, but the list is quite big (200 stores). Any tips and hints, please?

5
  • Are you attempting to turn these in to POJOs? Commented May 5, 2012 at 0:47
  • No, I only need to get product name + availibility as 2 Strings and then push tem into a hashmap. Commented May 5, 2012 at 0:56
  • That's not "nested JSON", that's plain old JSON. You just parse it. You can use a fancy-dancy Jacksonesque tool to parse into "POJOs", but you first should learn to just use a simple parser to parse it into Maps and Lists, the navigate through the Maps and Lists to access your data. This way you'll come to understand JSON much better. Commented Sep 27, 2014 at 1:34
  • You'd parse the above into a JSONObject, call it root, then do root.getObject("goods") to go the first level, producing another JSONObject (call it goods). Then goods.getArray("NY Store") to get a JSONArray called store. Then store.getObject(0) to get the first element of the array called storeElement, then storeElement.getString("product") will return "Teddybear". About 5 lines to fetch "Teddybear", if you put each step on a single line (which is advised, when you're starting out). Commented Sep 27, 2014 at 1:40
  • BTW, go to json.org and study the JSON syntax -- it only takes 5- 10 minutes to learn. Commented Sep 27, 2014 at 1:41

4 Answers 4

2

This is a quick intro for your specific use case into the Jackson library.

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class JSONTest {
    /**
     * @param args
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonGenerationException
     */
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        HashMap<String, ArrayList<InventoryItem>> fs = new HashMap<String, ArrayList<InventoryItem>>();
        for (int i = 0; i < 5; i++) {
            ArrayList<InventoryItem> its = new ArrayList<InventoryItem>();
            its.add(new InventoryItem("teddy", 20));
            its.add(new InventoryItem("diny", 10));
            fs.put(Long.toString(System.nanoTime()), its);
        }
        StoreContianer g = new StoreContianer(fs);
        ObjectMapper objm = new ObjectMapper();
        StringWriter sw = new StringWriter();
        objm.writeValue(sw, g);
        System.out.println(sw.toString());
        StoreContianer c = objm.readValue(
                "{\"goods\":{\"55278650620460\":[{\"product\":\"teddy\",\"available\":20},{\"product\":\"diny\",\"available\":10}],\"55278650631327\":[{\"product\":\"teddy\",\"available\":20},{\"product\":\"diny\",\"available\":10}],\"55278650628131\":[{\"product\":\"teddy\",\"available\":20},{\"product\":\"diny\",\"available\":10}],\"55278650582748\":[{\"product\":\"teddy\",\"available\":20},{\"product\":\"diny\",\"available\":10}],\"55278650624615\":[{\"product\":\"teddy\",\"available\":20},{\"product\":\"diny\",\"available\":10}]}}",
                StoreContianer.class);
        StringWriter sw2 = new StringWriter();
        objm.writeValue(sw2, c);
        System.out.println(sw2.toString());
    }
}

@JsonSerialize
class StoreContianer {
    private final HashMap<String, ArrayList<InventoryItem>> goods;

    public StoreContianer(@JsonProperty("goods") HashMap<String, ArrayList<InventoryItem>> goods) {
        this.goods = goods;
    }

    public HashMap<String, ArrayList<InventoryItem>> getGoods() {
        return goods;
    }
}

@JsonSerialize
class InventoryItem {
    private final String product;
    private final int available;

    public InventoryItem(@JsonProperty("product") String product, @JsonProperty("available") int available) {
        this.product = product;
        this.available = available;
    }

    public String getProduct() {
        return product;
    }

    public int getAvailable() {
        return available;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

why not use the library? http://www.json.org/java/

specifically,

public JSONObject(String source) throws JSONException {
        this(new JSONTokener(source));
}

9 Comments

Meh, that JSON library is pretty lousy for Java. There are much better ones out there, such as GSON or Jackson.
I tried to iterate through the JSONArray object, but it didn't work. JSONObject goods = new JSONObject(jsonInput); JSONArray stores = goods.toJSONArray("stores"); throws me an error
need more information, update your question with some details from this attempt.
because it is incredible slow
@MattBall It's not a lousy library; its usefulness depends on what's needed. The JSON in Java library does not require deserializing to a custom class - basic operations are performed using the post-parsing JSONObject which is all the OP needed. If I'm working with a response from a web service then I'll use Jackson and unmarhsal to my own classes but if I need a quick way to manipulate a JSON object directly (and not through my own POJO) I use the JSON in Java library.
|
0

I found this google library very powerful for parsing nested objects in JSON.

List<String> products = JsonPath.read(json, "$.goods.NY Store[*].product");

This will return you a list of all products in each "NY Store" list.

Comments

0
    //import java.util.ArrayList;
    //import org.bson.Document;

    Document root = Document.parse("{\n"
            + "   \"goods\":{\n"
            + "      \"NY Store\":[\n"
            + "         {\n"
            + "            \"product\":\"Teddybear\",\n"
            + "            \"available\":\"20\"\n"
            + "         },\n"
            + "         {\n"
            + "            \"product\":\"Mountain bike\",\n"
            + "            \"available\":\"0\"\n"
            + "         }]}}");

    System.out.println(((String) ((Document) ((ArrayList) ((Document) root.get("goods")).get("NY Store")).get(0)).get("product")));
    System.out.println(((String) ((Document) ((ArrayList) ((Document) root.get("goods")).get("NY Store")).get(0)).get("available")));
    System.out.println(((String) ((Document) ((ArrayList) ((Document) root.get("goods")).get("NY Store")).get(1)).get("product")));
    System.out.println(((String) ((Document) ((ArrayList) ((Document) root.get("goods")).get("NY Store")).get(1)).get("available")));

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.