Reputation: 13
I have the below json string that comes from the db. I have to read the json and return the equivalent java class. Json String:
{
"Items": [
{
"mode": "old",
"processing": [
"MANUAL"
]
},
{
"mode": "new",
"processing": [
"AUTO"
]
}
]
}
Items class
public class Items {
private String mode;
private List<String> processing;
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public List<String> getProcessing() {
return processing;
}
public void setProcessing(List<String> processing) {
this.processing = processing;
}
}
Here I am trying to read the above json string array using ObjectMapper.readValue()
method and convert it to List.
I have tried with the below code
ObjectMapper mapper=new ObjectMapper();
List<Items> actions = Arrays.asList(mapper.readValue(json, Items[].class));
and getting the error
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "actions" (class ), not marked as ignorable (2 known properties: "mode", "processing"])at [Source: (String)"{
"items":[
{
"mode": "old",
"processing": ["MANUAL"]
},
{
"mode": "new",
"processing": ["AUTO"]
}
]
}"; line: 2, column: 13]
Upvotes: 0
Views: 232
Reputation: 226
For the json itself, you can try to use this website to generate the pojo class https://www.jsonschema2pojo.org/
It really helpful to know what class that you need to parse the json. For the example that you've post, what you need is 2 classes.
This is POJO for the outer json.
public class ExampleObject {
@JsonProperty("Items")
public List<Item> items = null;
}
This one is for your Item class
public class Item {
@JsonProperty("mode")
public String mode;
@JsonProperty("processing")
public List<String> processing = null;
//Dont forget to put your setter getter in here.
}
After that, just use your code to parse that json into new class.
ObjectMapper mapper = new ObjectMapper();
List<Items> actions = Arrays.asList(mapper.readValue(json, ExampleObject.class));
Hope it helps, cheers
Upvotes: 1