1

I'm consuming a web service in my application that will return a list of ID's associated with a name. An example would look like this:

{
  "6502": "News",
  "6503": "Sports",
  "6505": "Opinion",
  "6501": "Arts",
  "6506": "The Statement"
}

How would I construct a POJO for Gson to deserialize to when all of the fields are dynamic?

2 Answers 2

3

How about deserializing into a map?

Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
String json = "{'6502':'News','6503':'Sports','6505':'Opinion','6501':'Arts','6506':'The Statement'}";
Map<String, String> map = gson.fromJson(json, mapType);

Using a map sounds reasonable for me (as Java is statically typed). Even if this could work (maybe using JavaCompiler) - accessing the object would not probably be much different from accessing a map.

Sign up to request clarification or add additional context in comments.

1 Comment

Thought I would end up having to do this. Thanks!
2

I don't know Gson that well but I suspect that's not possible. You'd have to know which fields are possible beforehand, although the fields might not be in the Json and thus be null.

You might be able to create classes at runtime by parsing the Json string, but I don't know whether that would be worth the hassle.

If everything is dynamic your best bet would be to deserialize the Json string to maps of strings or arrays etc. like other Json libraries do (I don't know whether Gson can do this as well, but the classes you need are commonly called JSONObject and JSONArray).

So your Json string above would then result in a Map<String, String>.

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.