Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

c# - how to parse json array using Litjson?

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,

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"}]
}]

how can i read this json array?

Note:I am using Litjson for parsing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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"]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...