0

I have this json:

{
    "details": {
        "interest": {
            "label": "example1",
            "value": "19,9",
            "symbol": "%"
        },
        "monthly_invoice": {
            "label": "example2",
            "value": "29",
            "symbol": "eur"
        },
        "start_fee": {
            "label": "example3",
            "value": "0",
            "symbol": "eur"
        },
        "monthly_pay": {
            "label": "example4",
            "value": "58",
            "symbol": "eur"
        }
    }
}

The Details object will contain a dinamical number of objects with the same properties (label, value, symbol). It is a way to create a class structure in java, using gson to receive this data without known the name of the objects contained (interest, monthly_invoice...)?

Thanks!

bhspencer
  • 13,086
  • 5
  • 35
  • 44
John Smith
  • 44
  • 5
  • I do not agree with the claim that this is a duplicate of the question linked to above. This question is specifically about how to serialize a JSON string that describes an object with unknown properties into a Java class. The answer is to use a Java Map. That is not mentioned in the question referenced as a duplicate. – bhspencer Feb 16 '15 at 19:29
  • I dont think that the question is a duplicate. The question is different and the correct answer is different. I wanted to use java not javascript and I was interested in the class structure and the attribute contained by this classes. – John Smith Feb 16 '15 at 19:54

1 Answers1

2

In your Java code "details" should be a

Map<String, Foo>

Where Foo is your class with the label , value and symbol properties. e.g. you JSON would parse into a class that looks like this:

public class TestObject {

    public Map<String, Foo> details;

    public static class Foo {
        public String label;
        public String value;
        public String symbol;
    }
}

Then in your code where you want to deserialize it to a Java instance you would do this:

    Gson gson = new Gson();
    TestObject testObject = gson.fromJson(json, TestObject.class);
    System.out.println(testObject.details.get("interest").label);
bhspencer
  • 13,086
  • 5
  • 35
  • 44