如何在Java中将列表数据转换为JSON

26

我有一个函数返回Java类中的List数据。现在根据我的需求,我需要将它转换成Json格式。

以下是我的函数代码片段:

public static List<Product> getCartList() {
    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
    }
    return cartList;
}

我尝试使用这段代码将其转换为 json,但是它会出现类型不匹配错误,因为函数的类型是List...

public static List<Product> getCartList() {
    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
    }

    Gson gson = new Gson();
     // convert your list to json
     String jsonCartList = gson.toJson(cartList);
     // print your generated json
     System.out.println("jsonCartList: " + jsonCartList);

     return jsonCartList;

        }
请帮我解决这个问题。

你尝试将List转换为Json了吗?展示一下你的工作。 - Jeevan Patil
使用GSON - Rahul
@JeevanPatil 先生,我刚刚尝试了您发布的代码... - vikas
@vikas 请看这个链接是否对你有帮助 - http://www.kodejava.org/examples/588.html - Jeevan Patil
8个回答

37

使用 gson 库会更简单。使用以下代码片段:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

将JSON字符串转换回Java对象

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);

先生,我尝试了以下代码,但出现了类型不匹配的错误:"public static List<Product> getCartList() { List<Product> cartList = new Vector<Product>(cartMap.keySet().size()); for(Product p : cartMap.keySet()) { cartList.add(p); } Gson gson = new Gson(); // 将列表转换为json String jsonCartList = gson.toJson(cartList); // 打印生成的json System.out.println("jsonCartList: " + jsonCartList); return jsonCartList; }" - vikas
因为函数在列表中并且返回字符串。 - vikas
你能把 List<Product> cartList = new Vector<Product>(cartMap.keySet().size()); 改成 List<Product> cartList = new ArrayList<Product>(cartMap.keySet().size()); 吗? - anubhava
或者更好的方法是:List<Product> cartList = new ArrayList<Product>(cartMap.keySet());,这样就不需要运行任何for循环了。 - anubhava
先生,它给出了类型不匹配的错误,因为它返回字符串,而函数在列表中。 - vikas
@Vikas:你不应该把上述代码放在“getCartList()”方法里:) 那个方法返回一个“List<Product>”,就让它保持原样。当你调用那个方法时,使用返回的值,并使用上面的Gson代码片段将从“getCartList()”方法返回的列表转换为JSON字符串。 - anubhava

20
public static List<Product> getCartList() {

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
        JSONObject formDetailsJson = new JSONObject();
        formDetailsJson.put("id", "1");
        formDetailsJson.put("name", "name1");
       jsonArray.add(formDetailsJson);
    }
    responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

    return cartList;

}

您可以按照以下格式获取数据

{
    "forms": [
        { "id": "1", "name": "name1" },
        { "id": "2", "name": "name2" } 
    ]
}

谢谢您的回复,先生。请告诉我在这段代码中应该添加什么内容:“formDetailsJson.put("...", "...");" - vikas
3
您需要将包含org.json.simple.JSONArray、org.json.simple.JSONObject类的相关jar文件添加到类路径中。 - PSR
先生,我需要知道在这段代码中该添加什么参数:"formDetailsJson.put("...", "..."); formDetailsJson.put("...", "...");" - vikas
那些JAR文件我已经添加了,先生。 - vikas
你需要在JavaScript中指定一个名称,以便访问它。 - PSR
先生,我正在尝试像这样做:“formDetailsJson.put(“title”,“description”,“price”);”,但它出现错误。 - vikas

7

尝试以下简单步骤:

ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();

0

使用Gson库尝试以下操作。

以前的转换列表格式如下:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

这里开始转换源代码。

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

转换后的Json结果为:
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

希望这能帮助到很多人!


0
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

List<String> ls =new  ArrayList<String>();

for(product cj:cities.getList()) {
    ls.add(cj);
    JSONObject formDetailsJson = new JSONObject();
    formDetailsJson.put("id", cj.id);
    formDetailsJson.put("name", cj.name);
    jsonArray.put(formDetailsJson);
}

responseDetailsJson.put("Cities", jsonArray);

return responseDetailsJson;

0
我编写了自己的函数来返回对象列表以填充组合框:
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
        try {
            Object[] args={};
            Class cl = Class.forName(kelas);
            Method getName = cl.getMethod(name, null);
            Method getLabel = cl.getMethod(label, null);
            String json="[";
            for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if(i>0){
                json+=",";
            }
            json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
            //System.out.println("Object = " + i+" -> "+o.getNumber());
            }
            json+="]";
            return json;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            System.out.println("Error in get JSON List");
            ex.printStackTrace();
        }
        return "";
    }

并且可以在任何地方调用它,例如:

String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");

2
在循环中使用 += 操作符来处理字符串是非常不好的做法。 - anstarovoyt
是的,我的数据量很小,所以影响不大。如果你处理大量数据,可以使用 StringBuilder 或 StringBuffer。 - Daniel Robertus

0
您可以使用以下方法,该方法使用Jackson库。
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
    if(StringUtils.isEmpty(jsonString)) return List.of();

        return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
                constructCollectionType(List.class, target));
    } catch ( JsonProcessingException | JSONException e) {
        e.printStackTrace();
        return List.of();
    }
}

-1
如果响应是List类型,res.toString()就足以将其转换为json格式,否则我们需要使用ObjectMapper mapper = new ObjectMapper(); String jsonRes = mapper.writeValueAsString(res);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接