简体   繁体   English

转换列表<integer>在 Java 中转至 JSON</integer>

[英]Convert List<Integer> to JSON in Java

How can I convert a List object in Java to a JSON object?如何将 Java 中的列表 object 转换为 JSON object?

For example, how can I convert this:例如,我如何转换它:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...

To this JSON:给这个 JSON:

{
    "List" : [1, 2, ...]
}

Thank you!谢谢!

If you want just to convert the list to json, you can use Gson:如果只想将列表转换为 json,可以使用 Gson:

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);

If you want that the key will be "List", you need to create a object with a member that call List and then convert it.如果您希望键为“List”,则需要创建一个 882829995402888 和一个调用 List 的成员,然后将其转换。

If you need to convert to String use the com.fasterxml.jackson.databind.ObjectMapper如果需要转换为字符串,请使用com.fasterxml.jackson.databind.ObjectMapper

Ex:前任:

        List<Integer> myList = new ArrayList<>();
        myList.add(1);
        myList.add(2);

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(myList);
            System.out.println("result = " + json);
            //System.out.println(json);
        } catch (JsonProcessingException e) {
            //
        }

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

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