如何获取包含JSONObject的列表大小?

问题描述 投票:0回答:2

我在列表中有jsonobject,其类型为string,列表包含两个json对象,但大小为4。

存放在清单中的JSONObject是 -

[{"size":"S", "id":11},  {"size":"8", "id":19}]

List<String> myList = new ArrayList<>(Arrays.asList(cart.split(","))); 

给出以上输出,但myList.size()给出4。

java json list
2个回答
1
投票

首先,您必须映射到对象,然后您将能够获得正确的对象计数,例如:

package com.ds;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;


public class Main {


    public static void main(String[] args) {

        String cart = "[{\"size\":\"S\", \"id\":11},  {\"size\":\"8\", \"id\":19}]";

        Type type = new TypeToken<ArrayList<CObject>>() {
    }.getType();

        ArrayList<CObject> cObjectList = (new Gson()).fromJson(cart, type);

        System.out.println(cObjectList);

        System.out.println(cObjectList.size());

    }

    public class CObject {

        private String id;
        private String size;

        public String getSize() {
            return size;
        }

        public void setSize(String size) {
            this.size = size;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "CObject{" +
            "id='" + id + '\'' +
            ", size='" + size + '\'' +
            '}';
        }
    }
}

上述代码的输出是:

[CObject{id='11', size='S'}, CObject{id='19', size='8'}]
2

希望这会帮助你。


0
投票
Use Object Mapper library.

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;

您的String对象需要转换为Java类对象,并使用该列表可以正确获取列表的大小。

你的代码就在这里。

String cart = ...;
ObjectMapper mapper = new ObjectMapper();
List<ClassName> classObjects= null;
try {
    classObjects= mapper.readValue(cart, new TypeReference<List<ClassName>>() {});
} catch (Exception e) {
    throw new IndsolvException(ErrorFactory.INTERNAL_SERVER_ERROR, e.getMessage());
}
© www.soinside.com 2019 - 2024. All rights reserved.