2

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"},
     ....
4
  • "not an option"? Why? Commented Apr 1, 2015 at 13:32
  • May be you are talking about JSON.parse look at this stackoverflow.com/questions/4935632/parse-json-in-javascript Commented Apr 1, 2015 at 13:35
  • So you have your json as String and you want to access given property directly? Or you have some sort of Map or JsonObject? Commented Apr 1, 2015 at 13:42
  • As a String or a text file. Commented Apr 2, 2015 at 9:37

2 Answers 2

4

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer! And what is the syntax for getting a sub-field, for example date.value?
Therefore you have to navigate into the deeper JSONObject. See my edit
Worked perfectly. Thank you for taking your time to explain it to me, I definitely grasp the matter now!
0

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

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.