简体   繁体   English

C#。 如何将复杂的JSON反序列化为某个对象?

[英]C#. How to deserialize complex JSON to some object?

I use pinterest API to get some info, for example pinterest API link 我使用pinterest API来获取一些信息,例如pinterest API链接

As you see, this link returns text in JSON format, and it's pretty complex, so simple 如您所见,此链接返回JSON格式的文本,它非常复杂,非常简单

Dictionary<string,string> 

unsuitable I guess. 我猜不合适。

What solution you can recommend to solve this task? 您可以推荐什么解决方案来解决此任务?

I would use an external API like Json.NET and either deserialize to a POCO object that you create or a JObject (Json.NET is still in the top3 of the most downloaded package on Nuget, no worries, it's here to stay). 我将使用外部API(例如Json.NET)并反序列化为您创建的POCO对象或JObject(Json.NET仍位于Nuget上下载量最大的软件包的top3中,不用担心,它会一直存在)。

The first would ensure that the data is conform out of the box, but forces you to declare the data class beforehand. 第一种方法可以确保数据开箱即用,但是会强制您事先声明数据类。 From the official doc of Json.NET 来自Json.NET的官方文档

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

The second is a kind of dynamic object that "accepts" any kind of data an let you pull from it at runtime (more dangerous, but tremendously more flexible). 第二种是一种动态对象,可以“接受”任何类型的数据,让您在运行时从中提取数据(比较危险,但非常灵活)。

JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));

JObject o = new JObject();
o["MyArray"] = array;

string json = o.ToString();
// {
//   "MyArray": [
//     "Manual text",
//     "2000-05-23T00:00:00"
//   ]
// }

Create class structure as per JSON response 根据JSON响应创建类结构

For example, 例如,

public class Pinner
{
    public string about { get; set; }
    public string location { get; set; }
    public string full_name { get; set; }
    public int follower_count { get; set; }
    public string image_small_url { get; set; }
    public int pin_count { get; set; }
    public string id { get; set; }
    public string profile_url { get; set; }
}


public class Pin
{
    public object attribution { get; set; }
    public string description { get; set; }
    public Pinner pinner { get; set; }
    public int repin_count { get; set; }
    public string dominant_color { get; set; }
    public int like_count { get; set; }
    public string link { get; set; }
    public Images images { get; set; }
    public Embed embed { get; set; }
    public bool is_video { get; set; }
    public string id { get; set; }
}

public class User
{
    public string about { get; set; }
    public string location { get; set; }
    public string full_name { get; set; }
    public int follower_count { get; set; }
    public string image_small_url { get; set; }
    public int pin_count { get; set; }
    public string id { get; set; }
    public string profile_url { get; set; }
}

public class Data
{
    public List<Pin> pins { get; set; }
    public User user { get; set; }
    public Board board { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public int code { get; set; }
    public string host { get; set; }
    public string generated_at { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}

Use JavaScriptSerializer , 使用JavaScriptSerializer,

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
  1. Create classes acording to your JSON object. 根据您的JSON对象创建类。 I suggest you to use json2csharp , it helps you to generate your classes easily. 我建议您使用json2csharp ,它可以帮助您轻松生成类。
  2. Use Json.NET for serialization and deserialization. 使用Json.NET进行序列化和反序列化。 In this link you can find more information about it. 在此链接中,您可以找到有关它的更多信息。

Thanks guys, I did what I wanted using this code 谢谢大家,我做了我想要的使用此代码

 public Program()
        {
            using (var client = new WebClient())
            {
                string str = client.DownloadString("https://api.pinterest.com/v3/pidgets/boards/Monokumagirl/anime-girls/pins/");

                JObject jobject = JObject.Parse(str);

                JToken pins = jobject["data"]["pins"];

                int i = 0;
                while(true)
                {
                    try {
                        var pin = pins[i];
                        Console.WriteLine(pin["images"]["237x"]["url"]);
                        i++;
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine(e.Message);
                        break;
                    }
                }

                Console.WriteLine("count: " + i);
            }

            Console.ReadLine();
        }

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

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