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"));
}