Reputation: 13
Here is the example json.
{
"foo1" : "...",
"foo2" : "...",
"foo3" : "...",
"foo4" : "..."
}
I want to deserialize it like this.
class Response {
List<Foo> foos;
}
I tried this, but not worked.
class Response {
...
@JsonProperty("foo\\d")
private void collect(String bar) {
foos.add(bar);
}
}
This worked. but I want to more simple thing.
@JsonProperty("foo1")
private void collect1(String bar) {
foos.add(bar);
}
@JsonProperty("foo2")
private void collect2(String bar) {
foos.add(bar);
}
.
.
.
Upvotes: 1
Views: 230
Reputation: 548
How about to convert object to map and then convert map to list
//This is some object
class Fruit{
private String name;
private int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return name+","+price;
}
}
class Response{
List<Fruit> fruits;
public Response() {
fruits = new ArrayList<Fruit>();
}
}
class Util{
public static Map<String, Object> jsonToMap(String jsonStr) {
Map<String, Object> map = null;
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(jsonStr, new TypeReference<Map<String,
Object>>(){});
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
public class Deserialize {
public static void main(String[] args) {
//1. Call jsonStr
String jsonStr = "{\r\n"
+ " \"fruit1\": {\r\n"
+ " \"name\": \"melon\",\r\n"
+ " \"price\": \"500\"\r\n"
+ " },\r\n"
+ " \"fruit2\": {\r\n"
+ " \"name\": \"banana\",\r\n"
+ " \"price\": \"1000\"\r\n"
+ " }\r\n"
+ "}";
//2. deserialize it to Map
Map<String, Object> map = Util.jsonToMap(jsonStr);
//System.out.println(map);
//{fruit1={name=melon, price=500}, fruit2={name=banana, price=1000}}
//3. add to fruit to fruits list of class Response
Response response = new Response();
map.forEach((k,v) ->{
// If json has key of fruit
if(k.contains("fruit")) {
final ObjectMapper mapper = new ObjectMapper(); // jackson's
objectmapper
final Fruit fruit = mapper.convertValue(v, Fruit.class);
response.fruits.add(fruit);
}
});
//melon,500
//banana,1000
response.fruits.stream().forEach(v -> System.out.println(v.toString()));
}
}
Upvotes: 0
Reputation: 2363
You should try @JsonAnySetter
annotation.
Example:
public class Test {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\n" +
" \"foo1\" : \"...\",\n" +
" \"foo2\" : \"...\",\n" +
" \"foo3\" : \"...\",\n" +
" \"foo4\" : \"...\"\n" +
"}";
Test test = objectMapper.readValue(json, Test.class);
}
@JsonAnySetter
void setInformation(String key, Object value) {
System.out.println(key + " " + value);
}
}
Output of the main()
method call is:
foo1 ...
foo2 ...
foo3 ...
foo4 ...
Upvotes: 2