Reputation: 825
I have a quite varying structure JSONObject. I am using json.simple to get values from the object like this:
String val1 = ((LinkedHashMap<String, String>) response.get("key1")).get("inner_key1");
String val2 = ((LinkedHashMap<String, String>) response.get("key1")).get("inner_key2");
int index1 = (int) ((ArrayList) response.get("index_key1")).get(0);
int index2 = (int) ((ArrayList) response.get("index_key2")).get(0);
int index3 = (int) ((ArrayList) response.get("index_key3")).get(0);
I am wondering if I can use a utility method to get these values with a better, more generic way? Also, I would like to avoid those casting too, is there any solution for that?
Upvotes: 1
Views: 81
Reputation: 3430
Since the keys in JSON are always the same you can create a class and specify the keys as instance varaibles. Now you can use Jackson library's Object Mapper
to convert the JSON string
to JSON Object
as shown in below code.
public class Vehicle{
private String brand = null;
private int doors = 0;
public String getBrand() { return this.brand; }
public void setBrand(String brand){ this.brand = brand;}
public int getDoors() { return this.doors; }
public void setDoors (int doors) { this.doors = doors; }
}
Insdie the main function you can write the below code:
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Vehicle vehicle= objectMapper.readValue(carJson, Vehicle.class);
System.out.println("car brand = " + vehicle.getBrand());
System.out.println("car doors = " + vehicle.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
Also, using Object Mapper
way you don't need to do the cast.
You can read more about it here.
Upvotes: 1
Reputation: 638
You could use GSON library provided by Google to map JSON to Java.
An example,
public class Example {
private String val1;
private String val2;
private ArrayList<int> index_key1;
private ArrayList<int> index_key2;
private ArrayList<int> index_key3;
///
// Getter Methods
///
public String getVal1() { return val1; }
public String getVal2() { return val2; }
public int getIndex1() { return index_key1.get(0); }
public int getIndex2() { return index_key2.get(0); }
public int getIndex3() { return index_key3.get(0); }
}
Then
Example ex = new Gson().fromJson(response.toString(), Example .class);
After that you should be good to go. There also is a library called Jackson which provides a similar solution to GSON.
Upvotes: 1