26

ListJavaクラスのようにデータを返す関数があります。今、私の必要に応じて、それを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このコードを使用して変換しようとしましたが、関数がリスト型であるため、型の不一致エラーが発生しています...

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;

        }

これを解決するのを手伝ってください。

4

7 に答える 7

34

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);
于 2013-03-11T06:59:58.003 に答える
19
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" } 
    ]
}
于 2013-03-11T06:52:23.373 に答える
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();
    }
}
于 2020-10-20T14:51:10.223 に答える
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");
于 2013-03-11T06:53:27.730 に答える