0

As you can see in the example below, the first item in the attributes array is an object consisting of two string properties. The second object consists of a string and array property. I would like to decode both of these types of JSON objects into a collection of Java objects.

How I can express this in a POJO java class to handle decoding JSON like this?

attributes:[
  {
    "attribute_code": "has_options",
    "value": "0"
  },
  {
    "attribute_code": "ewc_top_quick",
    "value": [
      {
        "label": "Display",
        "value": "12.5",
        "suffix": "''"
      },
      {
        "label": "Grafica Integrata",
        "value": "1",
        "suffix": ""
      }
    ]
  }
]
4
  • Apparently I have done the question wrong, so the downvoting, I will delete it, but can I known why? I'm not a native english speaker,so I suppose my english is not good enough to pose a question here Commented Apr 22, 2020 at 14:12
  • How can it be more precise? There is only one question. How I can map a array with multiple type in it. Nothing more, just one question and has been partially answered and the response is focused on a single problem. Why is not focused? There a single problem and a single question with a single technology. I have even shown an example with ONLY the single problem in the JSON. Commented Apr 22, 2020 at 14:48
  • Again the single question is: How can I map an array wich can contain either objects and string ? Commented Apr 22, 2020 at 14:52
  • I really need help on this I don't understand why this has been closed. Really disappointing Commented Apr 22, 2020 at 15:12

1 Answer 1

1

So, you can use Map<String, Object> fro this field.

class Attr {

    private String attribute_code;

    private Map<String, Object> value;
}

After this, you can work with this object.

Also, you can use @JsonAnySetter. It's something similar to the previous option.

And the best way to resolve your situation it's custom deserializer. I strongly recommended this option.

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

3 Comments

I don't think this will work, when the member is a string will not be set to a map
I think the easiest solution is to use: List<Map<String, Object>> Attributes; and then switch on type.
Yes. I think so.

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.