【问题标题】:What is the structure of JSON to be read by google-gsongoogle-gson要读取的JSON结构是什么
【发布时间】:2010-10-10 18:40:38
【问题描述】:

我想知道,鉴于以下 JSON,我如何生成一个 ResultSet 实例,它携带 Queryppb

package jsontest;

import com.google.gson.Gson;

/**
 *
 * @author yccheok
 */
public class Main {

    public static class ResultSet {
        public String Query;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        final String s = "{\"ResultSet\":{\"Query\":\"ppb\"}}";
        System.out.println(s);
        Gson gson = new Gson();
        ResultSet resultSet = gson.fromJson(s, ResultSet.class);
        // {}
        System.out.println(gson.toJson(resultSet));
        // null?
        System.out.println(resultSet.Query);
    }
}

目前,这是我得到的:

{"ResultSet":{"Query":"ppb"}}
{}
null

不修改String,如何获取正确的Java对象?

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    尝试构造一个新对象,调用gson.toJson(object),看看结果。

    我没有 gson,但是 jackson(另一个 object-to-json 映射器)打印了这个:

    {"Query":"ppb"}
    

    所以,你不包括类名。实际上,gson user guide 给出了一个例子来说明这一点。看BagOfPrimitives

    (最后一点 - 在 Java 中,公认的做法是变量是小写的 - 即 query 而不是 Query

    更新如果你真的不能改变json输入,你可以这样镜像结构:

    public static class Holder {
        public ResultSet ResultSet;
    }
    
    public static class ResultSet {
        public String Query;
    }
    

    (然后使用Holder h = gson.fromJson(s, Holder.class);

    【讨论】:

    • @Yan Cheng CHEOK 我不是这个意思。不管怎样,看看我的更新
    • 我无法控制 JSON 字符串。它是从服务器返回的。
    • 好的。我可以看到我错过了 Holder 课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 2018-12-29
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多