0

I have problem parsing dynamic JSON field name with GSON into Java Object. I have JSON like this:

{
...
"field_basic": "12.3",
"field_basic_country": "12.3",
"field_ex4": "2.7",
...
}

Field field_ex4 can have different names like field_ex1, field_ex2... I don't want to make all the atributes in Java class like this:

private String field_ex1;
private String field_ex2;
private String field_ex3;
private String field_ex4;
...

So my question is if there is posibility that this field is parsed into one universal filed name (like "field_exN") and that I also would know what values N is. There is always just one field_ex in JSON.

Thank you.

user4341206
  • 647
  • 1
  • 7
  • 26
  • I think that Jackson can do this with `@JsonAnyGetter` but Gson does not. See https://stackoverflow.com/questions/25551283/how-can-you-get-a-list-of-unrecognized-json-fields-in-gson-like-jacksons-jsona – Piotr Gwiazda Sep 27 '22 at 19:08
  • You have to option to not map your json to a java class put parse the tree. You can also iterate over all the fields an object has. Have a look here for parising json as a tree: https://www.tutorialspoint.com/gson/gson_tree_model.htm . If you want to know what fields exist have a look here: https://stackoverflow.com/questions/31094305/java-gson-getting-the-list-of-all-keys-under-a-jsonobject – Alex Sep 27 '22 at 19:21
  • 1
    In addition to @Alex's solution you can also deserialize the `JsonObject` as your model class with `Gson.fromJson(JsonElement, ...)` and then manually retrieve the field with dynamic name from the `JsonObject` and set the value for the model class instance. – Marcono1234 Sep 27 '22 at 19:54

0 Answers0