在Android中反序列化JSON字符串 [英] Deserializing JSON string in android

查看:236
本文介绍了在Android中反序列化JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的JSON字符串

I have JSON String that read as below

{   "Status":"Clear",    "Class": [{  <br>
        {"name":"personA", "available" : 1}, <br>
       {"name":"personB", "available" : 0}, <br>
       {"name":"personC", "available" : 0}, <br>
        {"name":"personD", "available" : 1} <br>
         }] }

如何反序列化上面的JSON字符串?

How do I deserialize the JSON String above?

我想到了使用JSONObject将整个JSON字符串放入其中的想法,但是却不知道如何获取对象的arraylist(Class对象的列表)并分配给arraylist< Class>.

I got the idea of using JSONObject to take in whole JSON String into it but no idea how to get the arraylist of object (the list of Class object) and assign to a arraylist<Class>.

非常感谢指导和帮助.

已更新:

已解决和解决方案显示

SOLVED AND SOLUTION SHOWN

我已经解决了这个问题,但是我想我必须解释我如何以及为什么使用这种解决方案.

I have solved this question but I think I have to explain how and why I used such solution.

因此,为了进一步解释我的问题,这是一个json字符串,最初是一个对象,该对象已被序列化并从Web服务发送到我的应用程序.

So to further explain my question, this is an json string that originally an object that got serialized and sent from a webservice to my apps.

原始对象是这样的:

 public class StatusJson
     {
         public String Status { get; set; }
         public List<Class> Class { get; set; }
     }

所以我要做的就是在我的android中声明一个完全相同的类,然后使用此代码

So what I have to do is just declare an exactly same class in my android then use this code

statusJson  statusJSON=g.fromJson(JSonString,StatusJson.class);

它将自动将json字符串解析为完全相同的类格式.

which will automatically parse the json string to the exact same class format.

如果您直接发送像我这样的JSON序列化类,希望这对您也有帮助.

Hope this will help you guys too if you are directly sending a JSON serialized class like me.

推荐答案

我建议您检查 Gson库.

您可以创建带有注释的类

You can create a class with anotations

private class ClassObj {
@SerializedName("personA") 
private final String personA;
....
}

然后

ClassObj object = gson.fromJson(jsonString, ClassObj.class);

它可以是复杂的对象,其中包含其他gson对象或Collection.尝试.

It can be complicated object, which contain other gson objects or Collection. Try.

这篇关于在Android中反序列化JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆