[英]how can i access json object in javascript and convert it into array in java?
[英]How can i convert JSON to Java object
嗨,我有一個以下格式的JSON
{
"elements":[
list1,
list2,
list3
]
}
其中list1,list2,list3都是javascript數組。
現在我可以從javascript文件傳遞給我的控制器(我使用spring mvc)。 現在我想使用正在發送的JSON中的數據。 我想將其映射到模型類並將其返回到另一個jsp頁面。 我還沒有創建模型。 我怎么能把它拉下來?
請幫忙。 提前致謝。
使用GSON將您的JSON轉換為java
YourModelClass obj= gson.fromJson(json, YourModelClass .class);
使用Gson ,首先需要創建一個表示JSON數據的類結構,這樣就可以創建一個這樣的類:
public class Response {
private List<List<YourObject>> elements;
//getter and setter
}
請注意,我使用類YourObject
因為您沒有指定數組包含的類型...例如,如果數組只包含字符串, YourObject
用String
替換YourObject
。 如果數組包含不同的對象,則必須創建表示JSON中數據的類,例如:
public class YourObject {
private String attribute1;
private int attribute2;
private boolean attribute3;
//getters and setters
}
然后,為了實際解析您的JSON響應,您只需要:
Gson gson = new Gson();
Response response = gson.fromJson(yourJsonString, Response.class);
並且您的JSON數據將用於填充您的類結構,因此您可以訪問這些字段,例如:
String attribute1 = response.getElements().get(i).get(i).getAttribute1();
嗨,我使用以下代碼,它的工作很棒。
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = jsonParser.parse(this.plan).getAsJsonArray();
ArrayList<PlanJson> planJsonList = new ArrayList<PlanJson>();
for(JsonElement jsonElement:jsonArray)
{
System.out.println(jsonElement);
PlanJson planJson = gson.fromJson(jsonElement, PlanJson.class);
planJsonList.add(planJson);
}
我發現它是最容易為我的json結構工作的。
您可以使用jackson庫。 見: http : //jackson.codehaus.org/
以下是一個示例: http : //www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
package com.mkyong.core;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// read from file, convert it to user class
User user = mapper.readValue(new File("c:\\user.json"), User.class);
// display to console
System.out.println(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.