Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial JSON retrieval with RestTemplate

I'm using Spring RestTemplate to send GET request to the third-party service. It returns huge JSON which represents a list of some entities. But every entity is really big and contains tons of unnecessary data. I need to get only three fields from every entity. How can I build my model to achieve it? For example if we have this JSON:

{
   "entity1": "foo",
   "entity2": "bar",
   "entity3": "...",
   "entity4": {
       "aaa": "...",
       "bbb": "...",
       "ccc": 5
   },
   "entity5": [
       "...",
       "..."
   ]
}, {
   "entity1": "foo",
   "entity2": "bar",
   "entity3": "...",
   "entity4": {
       "aaa": "...",
       "bbb": "...",
       "ccc": 5
   },
   "entity5": [
       "...",
       "..."
   ]
}

And I have a class:

public class SomeModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long entity1;
    private String entity2;    
}

How can I convert this JSON to the array of instances of this class?

like image 448
Alesto Avatar asked Oct 19 '22 04:10

Alesto


1 Answers

If you're using Jackson, you could annotate your model class with @JsonIgnoreProperties(ignoreUnknown = true), as such:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PosterDishModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long entity1;
    private String entity2;    
}

Basically, it instructs Jackson to discard any unknown properties in the received object.

Note that this does not prevent the transfer of the entire object over the network, the traffic will be the same, but the objects you'll deserialize into will not contain the unnecessary fields and data.

like image 102
Cristina_eGold Avatar answered Oct 21 '22 01:10

Cristina_eGold