简体   繁体   English

读取 String json 数组并转换为 List 对象

[英]Read String json array and convert to List object

I have the below json string that comes from the db.我有以下来自数据库的 json 字符串。 I have to read the json and return the equivalent java class.我必须阅读 json 并返回等效的 java 类。 Json String: json字符串:

{
 "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.在这里,我尝试使用ObjectMapper.readValue()方法读取上述 json 字符串数组并将其转换为 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] 

For the json itself, you can try to use this website to generate the pojo class https://www.jsonschema2pojo.org/对于json本身,可以尝试使用本网站生成pojo类https://www.jsonschema2pojo.org/

It really helpful to know what class that you need to parse the json.了解解析 json 所需的类真的很有帮助。 For the example that you've post, what you need is 2 classes.对于您发布的示例,您需要的是 2 个类。

This is POJO for the outer json.这是外部 json 的 POJO。

public class ExampleObject {

    @JsonProperty("Items")
    public List<Item> items = null;

}

This one is for your Item class这个是给你的 Item 类的

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.之后,只需使用您的代码将该 json 解析为新类。

ObjectMapper mapper = new ObjectMapper();
List<Items> actions = Arrays.asList(mapper.readValue(json, ExampleObject.class)); 

Hope it helps, cheers希望有帮助,加油

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM