【问题标题】:Convert Json to an specific Class将 Json 转换为特定的类
【发布时间】:2012-12-05 15:47:29
【问题描述】:

我正在尝试从维基百科检索文本以在 Android 应用程序上使用。我正在使用 Java。 我要做的第一件事是从特定文章中检索部分,将它们显示给用户,当用户单击一个部分时,通过另一个 http 请求获取部分文本。

所以,这两个请求是:

http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=sections

然后是这个:

http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=text&section=1

我的问题是:我应该创建什么样的 java 对象来存储信息,然后使用 .fromJSON() 将其转换为这些类?

感谢@NathanZ,我创建了这两个类:

public class WikiResponseSections {
    String title;
    List<Section> sections;
}

public class Section {
        int toclevel;
        String level;
        String line;
        String number;
        String index;
        String fromtitle;
        int byteoffset;
        String anchor;
}

但是,当我通过 Gson 将 HTTP 响应转换为这些对象并尝试读取字段“title”的值时,会触发一个错误:JavaNullPointerException。 这是我的转换代码:

InputStream stream = null;
try {
    stream = entity.getContent();
} catch (IllegalStateException e) {
    Log.e("Stream","ERROR illegalstateexception");
} catch (IOException e) {
    Log.e("Stream","ERROR exception");
}
reader = new BufferedReader(new InputStreamReader(stream));
GsonBuilder bldr = new GsonBuilder();
Gson gson = bldr.create();
WikiResponse = gson.fromJson(reader, WikiResponseSections.class);
if (WikiResponse != null){
    Log.i("WikiResponse",WikiResponse.getTitle()); //The error triggers HERE
    publishProgress();
}
else
    Log.i("WikiResponse","NULL");
}

再次感谢您的帮助

【问题讨论】:

    标签: java android json wikipedia


    【解决方案1】:

    您可以使用Google's Gson 库。 它的工作原理是这样的:

    InputStream source = ...; // your code to get the Json from a url
    Gson gson = new Gson();
    Reader reader = new InputStreamReader(source);
    MyResponse response = gson.fromJson(reader, MyResponse.class);
    

    MyResponse 是您的对象。创建 MyResponse 时,为您的字段提供与 Json 字段相同的名称和类型

    MyResponse 类可以如下:

    public class MyResponse{
        String title;
        ArrayList<sections>;
    }
    
    public class sections{
        int toclevel;
        String level;
        String line;
        String number;
        String fromtitle;
        long byteoffset;
        String anchor;
    }
    
    
    
    public class WikiResponseParse{
        Parse parse;
        public class Parse{
            String title, text;
        }
    }
    

    如果您不能使用 json 字段名称,因为它不符合 Java:

    添加以下导入:

    import com.google.gson.annotations.SerializedName;
    

    在你的班级里:

    @SerializedName("*")
    public String star;
    

    【讨论】:

    • 谢谢,但是,在第二个请求 (en.wikipedia.org/w/…) 中有一个名为“*”的字段。我该怎么办?
    • 似乎 WikiResponse 为空,这意味着 Gson 反序列化不起作用。 logcat中一定有警告。检查您的 WikiResponse 类是否与 Json 对象的结构完全匹配。
    • WikiResponse 不为空,但字段为空。此外,没有警告。我尝试创建这个类: class WikiResponseParse{ WikiResponseSections parse; } 但还是不行
    猜你喜欢
    • 2021-07-21
    • 2021-11-25
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多