如何在Java中像这样传递Json
我有以下的Json。请帮我用Java获取所有组件如何在Java中像这样传递Json,java,json,Java,Json,我有以下的Json。请帮我用Java获取所有组件 { "Result":{ "results":2, "tags":[ { "id":1, "name":"かわいい", "weight":34 }, { "id":4, "nam
{
"Result":{
"results":2,
"tags":[
{
"id":1,
"name":"かわいい",
"weight":34
},
{
"id":4,
"name":"すっぴん",
"weight":12
}
]
}
}
请帮忙 使用以下两个模型类,并将其映射到JSONObject类
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Result")
public class Result {
int results;
List<Tags> tags;
public int getResults() {
return results;
}
public void setResults(int results) {
this.results = results;
}
public List<Tags> getTags() {
return tags;
}
public void setTags(List<Tags> tags) {
this.tags = tags;
}
}
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="tags")
public class Tags {
int id;
String name;
int weight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
创建一个名为json的映射
创建一个名为result的映射,并使用键result将其插入json
使用键“结果”将值2插入结果
创建一个列表,称之为标记,并使用键标记将其插入到结果中
创建一个映射,称之为tagEntry
插入键/值对id:1,名称:かわいい, 重量:34分
将标记项插入标记中
对第二个标记项值重复最后3个步骤。确保创建一个新的标记项映射
将json序列化为json字符串
还是你想走另一条路?如果是这样的话,只需做相反的事情。简单地使用一个模型类,并使用gson依赖关系将json映射到一个类模型并且您的代码被标记为低质量的答案,请提供一些解释:
import org.json.JSONObject;
import com.google.gson.Gson;
public class test {
public static void main(String[] args) throws ClassNotFoundException {
//Result result = new Result();
String jsonBody =" { \"Result\":{ \"results\":2, \"tags\":[ { \"id\":1, \"name\":\"fghgf\", \"weight\":34 }, { \"id\":4, \"name\":\"fghfgh\", \"weight\":12 } ] }} ";
JSONObject jsonObject = null;
jsonObject = new JSONObject(jsonBody);
for (int x = 0; x < jsonObject.getJSONObject("Result").length(); x++) {
JSONObject jObject = new JSONObject();
jObject.put("Result", jsonObject.getJSONObject("Result"));
String theType = "class path." + "Result";
Class<?> theClass = Class.forName(theType);
Gson converter = new Gson();
Result result = (Result) converter.fromJson(jsonObject.getJSONObject("Result").toString(), theClass);
}}
}
import org.json.JSONObject;
import com.google.gson.Gson;