how can i consume JSON response with many JsonProperty name in java

1.1k views Asked by At

i'm trying to consume a Json response using RestTemplate in java with Jackson annotations, and i have a resource that have many name properties like so:

{
        -name1:{
            id:2,
            price:12,
            name:"Bob:
        },
        -name2:{
            id:111,
            price:1.1,
            name:"Ron:
        },
        -name3:{
            id:10,
            price:33,
            name:"jhon:
        },
    }

and the list go on like this. this is my code of how to get one of the entities, like name1 object:

public class Class1 {
    private RestTemplate restTemplate;
    private String url = "https://url.com/api";
    private Response response;
    private Market market ;
    public class1(){
        restTemplate = new RestTemplate();
        response = restTemplate.getForObject(url,Response.class);
    }
    @Override
    public Market getResults() {
        market = response.getResult();
        System.out.println(Market);
        return null;
    }
}

and the response class is like so :

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
@NoArgsConstructor
public class Response {
    @JsonProperty("name1")
    private Market result;
}

how can i get all those elements as an array or ArrayList? this API is from 3rd party website and there's many entities liek that in the Json response. thanks in advance.

2

There are 2 answers

0
ian1095 On BEST ANSWER

So in the Json above, it is not an array but a list of key value pair.

This is what an array looks like in Json:

{ 
  marketResults: [
        {
            id:2,
            price:12,
            name:"Bob:
        },
        {
            id:111,
            price:1.1,
            name:"Ron:
        },
        {
            id:10,
            price:33,
            name:"jhon:
        }
     ]
    }

Then what you could have done is:

public class Response {
    private List<Market> marketResults;
}

But since your example is a map, you need to to use a MAP

public class Response {
    private Map<String, Object > marketResults;
}

That post actually similar to yours: Reading JSON map structure via spring boot

0
enator On

If you can use Gson library that has native support for this use-case. Keeps your code clean and typed.

@Getter
@Setter
public class Response {
    @SerializedName(value = "name1", alternate={"name2","name3"})
    private Market result;
}

@SerializedName is the @JsonProperty equivalent in Gson.