1

I use Java Spring in my project.

I need to parse JSON into java class.

Example of the JSON:

[
  {
    "Id":"aaa1"
    "Data1":"test11"
    "Data2":"test12"
    "url1": "https://...someimg11.png",
    "url2": "https://...someimg12.png",
  },
  {
    "Id":"aaa2"
    "Data1":"test21"
    "Data2":"test22"
    "url1": "https://...someimg21.png",
    "url2": "https://...someimg22.png",
  },
  {
    "Id":"aaa3"
    "data1":"test31"
    "data2":"test32"
    "url1": "https://...someimg31.png",
    "url2": "https://...someimg32.png",
  }
 ]
 

And here the Java class that json above should be parsed to:

  class Info{
    @JsonProperty("Id")
    public String id;
    
    @JsonProperty("Data1")
    public String data1;
    
    @JsonProperty("Data2")
    public String data2;
    
    //parse to here url1 and url2 properties from json doc
    public List<String> urls;
 }
 

As you can see I have no issues to parse properties, except the last properties in JSON url1 and url2, the properties of JSON file url1 and url2 should be parsed into URLs property of type List.

My question is, how can I parse the two properties of JSON inside the single property in the class of type list of strings?

UPDATE I can use @JsonAnySetter annotation as suggested on one of the answers, but in this case, I will need to initialize the urls property, otherwise, I get this error on parsing:

Cannot invoke "java.util.List.add(Object)" because "this.urls" is null

In case if I use @JsonAnySetter annotation how can I init urls property?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • It is better to use tow objects, entity and DTO objects. – Nurbol Mar 01 '21 at 17:57
  • Use `JsonAnySetter` annotation and create collection directly in class before annotated method will be invoked. See similar solution: [Map JSON key-value to class in java](https://stackoverflow.com/questions/63994359/map-json-key-value-to-class-in-java/63995252#63995252) – Michał Ziober Mar 01 '21 at 20:03
  • Better way, to have urls as array in JSON object. In future, if you have to add another url then it will need code changes as well. – Parul Mar 01 '21 at 20:21

1 Answers1

1

You can do it using @JsonAnySetter annotation and I don't if there is any easier way of using patterns or wildcards

class Info{

    @JsonProperty("Id")
    public String id;

    @JsonProperty("Data1")
    public String data1;

    @JsonProperty("Data2")
    public String data2;

     //parse to here url1 and url2 properties from json doc
     public List<String> urls = new ArrayList<>();

     @JsonAnySetter
     public void add(String key, String value) {
      if(key.equals("url1") || key.equals("url2")) {
           urls.add(value);
        }
    }
  }
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98