简体   繁体   中英

get nested Object using json-simple - Wildcard for parent Node

I want to retrieve "name" values and store them in an Arraylist from a JSON file in Java. I am using JSON-simple library Here is an example of my "file.json":

{
  "111": {

    "customer": {

        "name": "John Do",
        "Height": 5.9,
        "City": "NewYork"
    }

  },
  "222":{

    "customer": {

        "name": "Sean Williams",
        "Height": 6,
        "City": "Los Angeles"
    }
  }
}

Id numbers "111" and "222" are not significant for my program and they are randomly generated so I am not able to use jObject.get() as the values will constantly be changing. I tried searching for a wildcard for the parent Node and then go to child node customer and then name but haven't found such thing.

Here is my code so far:

import java.io.*;
import java.util.ArrayList;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class npTest {

    public static void main(String[] args) throws IOException, ParseException {

        try {
            JSONParser jParser = new JSONParser();
            JSONObject jObject = (JSONObject) jParser.parse(new FileReader("file.json"));

//Notes

    } catch (FileNotFoundException e) {
        System.out.print("File not found!");
    }

}

}

Notes: methods I have tried require jObject.get("id") . Also I noticed I am not able to store the JSONObject in another JSONObject, for example: JSONObject parentObj = new JSONObject(jObject.get("111"));

You can iterate through the keys in a JSONObject using the keySet() method. Then pull out your "customer" and get their name.

JSONParser jParser = new JSONParser();
JSONObject jObject = (JSONObject) jParser.parse(new FileReader("c:\\file.json"));

for(Object key : jObject.keySet()) {
    JSONObject customerWrapper = (JSONObject)jObject.get(key);
    JSONObject customer = (JSONObject)customerWrapper.get("customer");
    System.out.println(customer.get("name"));
}

JSONObject implements the Map interface. So you could query for all map keys with normal Java syntax:

for (Object innnerO : jObject.values()){
  JSONObject customerO = (JSONObject)((JSONObject)innerO).get("customer");
}

Note: This is written out of my head without compiler. So there might me errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM