如何使用Litjson解析JSON数组? [英] how to parse json array using Litjson?

查看:2690
本文介绍了如何使用Litjson解析JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中我正在使用来自服务器的json格式的数据. 但是我能够解析普通的json数据,但是无法解析带有数组的json数据,

I am developing an application in which i am using data came from server in the json format. However i am able to parse normal json data but failed to parse the json data with arrays,

json响应在下面给出,

the json response is given below,

[{"id_user":"80","services":
    [{"idservice":"3","title":"dni-e","message":"Texto para el dni-e"},
     {"idservice":"4","title":"Tarjeta azul","message":"Texto para la tarjeta azul"}]
}]

我如何读取此json数组?

how can i read this json array?

注意:我正在使用Litjson进行解析.

Note:I am using Litjson for parsing.

推荐答案

您应该创建以下POCO对象:

You should create yourselft following POCO objects:

public class Service
{
    public int idservice { get; set; }

    public string title { get; set; }

    public string message { get; set; }
}

public class UserServices
{
    public int id_user { get; set; }

    public List<Service> services { get; set; }
}

LitJSON将立即反序列化此序列:

LitJSON will deserialize this out-of-the-box:

UserServices services = JsonMapper.ToObject<UserServices>(rawJson);

作为替代方案,您可以使用非通用变量(下面的示例会将所有数据写入控制台):

As an alternative you can use non-generic variant (below sample would wrote all data to the console):

JsonData data = JsonMapper.ToObject(rawJson);
Console.WriteLine("User id: {0}", data["id_user"]);
Console.WriteLine("Services:");
for (int i = 0; i < data["services"].length; i++)
{
    Console.WriteLine ("    Id: {0}; Title: {1}; Message {2}", data["services"][i]["idservice"], data["services"][i]["title"], data["services"][i]["message"]);
}

这篇关于如何使用Litjson解析JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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