Java Gson json无法获取结果
请给我一个json响应字符串,如下所示:Java Gson json无法获取结果,java,json,gson,Java,Json,Gson,请给我一个json响应字符串,如下所示: {"result":{"id":21456,"name":"3mm nail","type":"2" }} 这是我的代码: class rootObj{ List<Result> result; } public class Result { @SerializedName("id") public String idItem; @SerializedName("name") public Str
{"result":{"id":21456,"name":"3mm nail","type":"2" }}
这是我的代码:
class rootObj{
List<Result> result;
}
public class Result {
@SerializedName("id")
public String idItem;
@SerializedName("name")
public String name;
}
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
Result result = gson.fromJson(json,Result.class);
System.out.println(result.name);
}
给巴卢斯的Thx给了我这个想法。
在JSON字符串中,结果属性是对象而不是数组。因此,要使它与两个Java类(rootObj和Result)一起工作,您需要在{brates}周围添加[bracket] 原创的 新的 此代码适用于我:
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class TestGson {
private static final String NAME = "3mm nail";
@Test
public void testList() {
final String json = "{\"result\":[{\"id\":21456,\"name\":\"" + NAME + "\",\"type\":\"2\" }]}";
Gson gson = new Gson();
ListWrapper wrapper = gson.fromJson(json, ListWrapper.class);
assertEquals(NAME, wrapper.result.get(0).name);
}
static class ListWrapper {
List<Result> result;
}
static class ObjectWrapper {
Result result;
}
static class Result {
@SerializedName("id")
public int idItem;
@SerializedName("name")
public String name;
}
}
导入静态org.junit.Assert.assertEquals;
导入java.util.List;
导入org.junit.Test;
导入com.google.gson.gson;
导入com.google.gson.annotations.SerializedName;
公共类TestGson{
专用静态最终字符串名称=“3mm钉子”;
@试验
公共void测试列表(){
最后一个字符串json=“{\'result\':[{\'id\':21456,\'name\':\'+name+“\”,\'type\':\'2\'}];
Gson Gson=新的Gson();
ListWrapper=gson.fromJson(json,ListWrapper.class);
assertEquals(名称,包装器.result.get(0).NAME);
}
静态类ListWrapper{
列出结果;
}
静态类对象包装器{
结果;
}
静态类结果{
@序列化名称(“id”)
公共国际项目;
@序列化名称(“名称”)
公共字符串名称;
}
}
参考..它解释了如何在不使用GSON的情况下解析json
我不知道GSON,但有两件事跳出来了:1。您要求它将数字(id
)视为字符串。这是故意的吗?Gson会自动这么做吗?2.您尚未映射类型
属性,Gson是否愿意省略属性?id确实如此,关于我刚刚编辑的类型,它是正确的。在结果类中,您没有声明“type”对象?
{"result":{"id":21456,"name":"3mm nail","type":"2" }}
{"result":[{"id":21456,"name":"3mm nail","type":"2" }]}
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class TestGson {
private static final String NAME = "3mm nail";
@Test
public void testList() {
final String json = "{\"result\":[{\"id\":21456,\"name\":\"" + NAME + "\",\"type\":\"2\" }]}";
Gson gson = new Gson();
ListWrapper wrapper = gson.fromJson(json, ListWrapper.class);
assertEquals(NAME, wrapper.result.get(0).name);
}
static class ListWrapper {
List<Result> result;
}
static class ObjectWrapper {
Result result;
}
static class Result {
@SerializedName("id")
public int idItem;
@SerializedName("name")
public String name;
}
}