Reputation: 2725
I have a very heavy JSON with lots of parameters which I want to convert to a Java object containing just a few of them.
Direct conversion such as this
DataObject obj = gson.fromJson(br, DataObject.class);
is not an option.
How can I access individual fields within objects (just value
under date
and type
under attributes
under completion_date
)?
JSON example:
{"results":[
{"date":{
"attributes":{
"type":null},
"value":"December 13, 2010"},
"is_structured":"No",
"completion_date":{
"attributes":{
"type":"Anticipated"},
"value":"March 2016"},
....
Upvotes: 2
Views: 5786
Reputation: 466
If you don't want to directly convert your input to the expected Object you could create a JSONObject
from your input like
JSONObject root = new JSONObject(input);
and then navigate from there exactly to the attribute you need e.g.:
root.getJSONArray("results").getJSONObject(0).getString("is_structured");
EDIT: (receive value
under date
)
root.getJSONArray("results").getJSONObject(0).getJSONObject("date").getString("value");
Upvotes: 4
Reputation: 20885
You can have just the fields you need in your bean definition. For example, given the following JSON
{
firstName: 'It',
lastName: 'works',
ignoreMe: '!!!'
}
the bean definition does not contain ignoreMe
:
public class Contact {
public String firstName; // setter and getter
public String lastName; // setter and getter
}
But it works with Gson:
Gson gson = new Gson();
Contact contact = gson.fromJson(new FileReader(new File("test.json")), Contact.class);
System.out.println("It worked!");
Upvotes: 0