Gson json无法得到结果

时间:2013-03-29 12:03:16

标签: 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 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);
}

但结果是null :( Thx提前。

所以..这段代码就是我的目标:

class ResultData{

    private Result result;
    public class Result {
        private String id;
        private String name;

    }

}


...
Gson gson = new Gson();
ResultData resultData = new Gson().fromJson(json, ResultData.class);

System.out.println(resultData.result.id);
System.out.println(resultData.result.name);
对BalusC来说,Thx给了我关于它的想法。 Java - Gson parsing nested within nested

2 个答案:

答案 0 :(得分:2)

在您的JSON字符串中,您的结果属性是Object而不是Array。因此,为了使它适用于您的两个Java类(rootObj和Result),您需要在{braces}周围添加[括号] 原始

{"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;
    }

}

答案 1 :(得分:0)

参考this ..解释如何在不使用json的情况下解析GSON