0

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] 
1
  • This is not a JSON formatted string. Commented Jun 6, 2022 at 7:13

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.