【问题标题】:How to convert list data into json in java如何在java中将列表数据转换为json
【发布时间】:2013-02-26 06:49:06
【问题描述】:

我有一个函数在 java 类中以 List 的形式返回数据。现在根据我的需要,我必须将其转换为Json 格式。

下面是我的函数代码sn-p:

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?展示你的作品。
  • 使用GSON
  • @JeevanPatil 先生,我尝试使用刚刚发布的代码...
  • @vikas 看看这对你有没有帮助 - kodejava.org/examples/588.html

标签: java json list


【解决方案1】:

您可以使用以下使用 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();
    }
}

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      【解决方案3】:

      试试这些简单的步骤:

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

      【讨论】:

        【解决方案4】:

        使用 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}]
        

        希望这能帮助很多人!

        【讨论】:

          【解决方案5】:
          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("...", "...");"
          • 你需要将相关的jar文件添加到包含org.json.simple.JSONArray,org.json.simple.JSONObject类的类路径中。
          • 先生,我需要知道在这个 "formDetailsJson.put("...", "..."); formDetailsJson.put("...", "中添加什么作为参数。 ..");"
          • 还有我添加的那些jar文件,先生
          • 你需要在javascript中输入你要访问的名字
          【解决方案6】:

          使用gson 会简单得多。使用以下代码 sn -p:

           // 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 getCartList() { List cartList = new Vector(cartMap.keySet().size( )); for(Product p : cartMap.keySet()) { car​​tList.add(p); } Gson gson = new Gson(); // 将你的列表转换为 json String jsonCartList = gson.toJson(cartList); //打印生成的 json System.out.println("jsonCartList: " + jsonCartList); return jsonCartList; }"
          • 因为函数在 List 并且它正在返回字符串
          • 你能把List&lt;Product&gt; cartList = new Vector&lt;Product&gt;(cartMap.keySet().size());改成这个:List&lt;Product&gt; cartList = new ArrayList&lt;Product&gt;(cartMap.keySet().size());
          • 或者更好:List&lt;Product&gt; cartList = new ArrayList&lt;Product&gt;(cartMap.keySet()); 然后不需要运行任何 for 循环。
          • 先生它在返回字符串并且函数在列表中时给出类型不匹配错误
          【解决方案7】:

          我编写了自己的函数来返回填充组合框的对象列表:

          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");
          

          【讨论】:

          • 使用 += for string 在循环中是非常糟糕的做法
          • 是的,我只有一点点数据,所以影响不大..如果您处理大量数据,您可以使用 StringBuilder 或 StringBuffer。
          猜你喜欢
          • 2012-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-08
          • 2017-04-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-30
          相关资源
          最近更新 更多