我有一个在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;
}
请帮我解决这个问题。
答案 0 :(得分:28)
使用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);
// 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);
答案 1 :(得分:16)
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" }
]
}
答案 2 :(得分: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");
答案 3 :(得分: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}]
希望这会对很多人有所帮助!
答案 4 :(得分:0)
尝试以下简单步骤:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
答案 5 :(得分: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;
答案 6 :(得分:0)
您可以使用以下使用Jackson库的方法
--enable-local-file-access