Reputation: 803
I have looked for other post in stack overflow but none of them work for me. Here is the piece of code:
public class Forward implements Serializable {
private List<String> freq;
public List<String> getFreq() {
System.out.println("Print Freq::: --> " + freq);
return freq;
}
public void setFreq(List<String> freq) {
this.freq = freq;
}
}
The JSON string is:
{"forward":[{"freq":"78000000"}]}
My mapper is:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
String jsonString = mapper.writeValueAsString(result);
If I remove List freq and change to String freq it works but my JSON can contain one or more freq so I need to create a List.I get exception as:
Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream
Upvotes: 1
Views: 22126
Reputation: 34920
DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY
works fine in order to deserialize "freq":"78000000"
fragment as value of List<String> freq
list.
But you have another problem: your json
contains explicit array of forward
. In order to deserialize this entire json
you need to have some kind of wrapper class, say:
public class ForwardWrapper {
private List<Forward> forward;
public List<Forward> getForward() {
return forward;
}
public void setForward(List<Forward> forward) {
this.forward = forward;
}
}
In this case
ForwardWrapper fw = mapper.readValue("{\"forward\":[{\"freq\":\"78000000\"}]}", ForwardWrapper.class);
will deserialize it perfectly.
Upvotes: 2