繁体   English   中英

使用gson库将Json反序列化为Java类

[英]Deserializing Json to java classes using gson library

在此处输入图片说明 我有这两节课:

public class Root {
    public ProfileInfoResult ProfileInfoResult = new ProfileInfoResult();
}

public class ProfileInfoResult {
    public String joiningYear;
}

这是我必须反序列化的json字符串:

{"ProfileInfoResult":{"joiningYear":"2009"}}

这是反序列化的代码:

Gson gson = new Gson();
JSONObject obj = new JSONObject(responseString); //responseString= {"ProfileInfoResult":{"joiningYear":"2009"}}
Root resultObj = new Root();
String resStr = obj.toString();
try
{
    resultObj = gson.fromJson(resStr, Root.class);
}
catch(Exception e)
{
    Log.i("myyyy", e.getMessage());
    e.printStackTrace();
}

Java调试表明resultObj无法解析为变量。

String str = "{\"ProfileInfoResult\":{\"joiningYear\":\"2009\"}}";

    Root root = new Root();

    Gson gson = new Gson();
    root = gson.fromJson(str, Root.class);
    TextView b = new TextView(context);
    b.setText(root.ProfileInfoResult.joiningYear);

这很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM