0

I have a JSON string coming from a server, and I have no control over it.
I generated the Java classes through programmatic usage of the jsonschema2pojo library.
I am using GSON to deserialize the JSON into my Java objects.

Here is an example of the JSON.

"description_by_id": {
    "50": {
        "field1": "value1",
        "field2": "value2",
        "field3": "value3"
    }
}

That "50" subclass is actually just 1 of 18 classes that are similarly named as a number.
When jsonschema2pojo generates the Java class, it understandably prepends an underscore to create the class name (so, _50).

jsonschema2pojo generates the DescriptionById class with this member:

@JsonProperty("50") private com.me.models._50 _50;

And the getter looks like this (setter is similar):

@JsonProperty("50") public com.me.models._50 get50() { return _50; }

I am using GSON like this:

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

But the _50 object and the other 17 like it are all null after GSON is done, and I have checked that the corresponding spots in the JSON are actually filled in with real values.

Is there anything along this chain that I can do to get it working properly without needing to manually hack around the issue?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
User51610
  • 453
  • 5
  • 18

1 Answers1

1

That "50" subclass is actually just 1 of 18 classes that are similarly named as a number

And what happens when you get one additional ID that you don't have a Java class for? Gson won't know what to do with it...

Don't make classes. Use a Map.

Make this "inner" POJO

public class Inner {

    private String field1;
    private String field2;
    private String field3;

}

And the outer POJO

public class Outer {
    private TreeMap<String, Inner> description_by_id;
}

And you would then have someOuter.getDescriptionById("50").getField1()

(Add back in the Gson attributes as necessary)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • The nature of the server application means that these classes are fixed at 18 and that their names won't change. It's very static. In any case, can what you are describing be done automatically with GSON? – User51610 Nov 16 '17 at 06:06
  • What do you mean automatically? Are all 18 classes containing the same "inner" content? If so, having unique classes for each one is still a bad design. – OneCricketeer Nov 16 '17 at 07:01
  • For automatically - meaning my usage of GSON in my original question. Or will I need to hack around before/after the GSON call? As for the inner content, all 18 classes have the same field names/types, they're just different values. I agree on the design comment, although I have no control over anything regarding this server, it's design, code, etc.; I am purely a consumer. – User51610 Nov 16 '17 at 16:35