简体   繁体   中英

How i can convert this JSON to Object in C#?

for two days I have been trying to understand how to move this JSON to an object in C#. I read a lot of topics and tried several ways to solve my problem, but still haven't solved it. My JSON looks like this (cropped).

{
    "data": [{
        "id": 5643793,
        "title": "It's a Title",
        "description": "It's a Description.",
        "tags": "#tag1 #tag2 #tag3 #tag4",
        "source_url": "https:\/\/p.dw.com\/p\/3geny",
        "vote_count": 120,
        "bury_count": 17,
        "comments_count": 33,
        "related_count": 0,
        "date": "2020-08-10 09:43:32",
        "author": {
            "login": "lnwsk",
            "color": 2,
            "avatar": "https:\/\/www.api.page.com\/cdn\/c3397992\/lnwsk_MfQz8MEQb2,q150.jpg"
        },
        "preview": "https:\/\/www.api.page.com\/cdn\/c3397993\/link_1597045214DgzqxRGEmy2UlpPZwaWfhI,w104h74.jpg",
        "plus18": false,
        "status": "promoted",
        "can_vote": true,
        "is_hot": false
    }],
    "pagination": {
        "next": "https:\/\/api.page.com\/links\/promoted\/appkey\/X*******4y\/page\/2\/"
    }
}

As you can see, there is an "element within an element" here (eg author or pagination (eg pagination I would like to get rid of)) and that is what gives me the most problem.

Here is my class where I have all the code to read the API:

using Newtonsoft.JSON;

public class PageAPI
{
    public class Product
    {
        public string[] title { get; set; }
        public double[] description { get; set; }
        public string[] tags { get; set; }
        public string[] source_url { get; set; }
        public string[] vote_count { get; set; }
        public string[] bury_count { get; set; }
        public string[] comments_count { get; set; }
        public string[] related_count { get; set; }
        public string[] date { get; set; }
    }

    public async Task<Product> GetDataAsync()
    {
        string url = "https://api.page.com/";
        string apisign = "6*********c1fe49a23f19ad6b2";
        string requestParams = "links/promoted/appkey/X*******y";

        Product obj = null;

        // HTTP GET.  
        using (var client = new HttpClient())
        {
            // Setting Base address.  
            client.BaseAddress = new Uri(url);
            // Setting content type.  
            client.DefaultRequestHeaders.Add("apisign", apisign);
            // Initialization.  
            HttpResponseMessage response = new HttpResponseMessage();
            // HTTP GET  
            response = await client.GetAsync(requestParams).ConfigureAwait(false);
            // Verification  
            if (response.IsSuccessStatusCode)
            {
                try
                {
                    // Reading Response.  
                    string result = response.Content.ReadAsStringAsync().Result;
                    obj = JsonConvert.DeserializeObject<Product>(result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show(ex.Message);
                }

            }
            else
            {
                obj = null;
            }
        }
        return obj;
    }
}

in the Form where I want to get data from the "PageAPI" class I have:

        private async void Form1_LoadAsync(object sender, EventArgs e)
        {
            var task = api.GetMainAsync();
            task.Wait();
            var data = task.Result;
            label1.Text = data.title[0];
        }

And... this doesn't works - on label1.Text = data.title[0]; i get error PageAPI.Product.title.get returned null Thanks for any help!

You are missing the Root class that has "data" and "pagination" properties. Create Root class and deserialize to it and then get the data you need. Also, your Product class will have only strings.. not string[].

public class RootObject
{
    public List<Product> data { get; set; }
}

public class Product
{
    public string title { get; set; }
    public double description { get; set; }
    public string tags { get; set; }
    public string source_url { get; set; }
    public string vote_count { get; set; }
    public string bury_count { get; set; }
    public string comments_count { get; set; }
    public string related_count { get; set; }
    public string date { get; set; }
}

// and deserialize it 
var rootObj = JsonConvert.DeserializeObject<RootObject>(result);
obj = rootObj.data.FirstOrDefault();

data object is an array... you can loop through it to work with All the items. In above example, i used FirstOrDefault() to get the first item from the object. Also note that when you access this data, you would not access it via [0]. Simply use

label1.Text = data.title;


Side Note

If you want the pagination property as well, create another class to get the name from pagination object.

public class RootObject {
    public List<Product> data {get;set;}
    public Pagination pagination {get;set;}
}

public class Pagination {
    public string next {get;set; }
}

and when you deserialize your json, you would access the pagination by using,

Console.WriteLine(rootObj.pagination.next); // prints the url

How to get All the Product Names displayed

This is how you would go about getting a list of All the titles in the data object.

foreach (var product in rootObj.data) 
{
    Console.WriteLine(product.title);
    Console.WriteLine(product.description);
    Console.WriteLine(product.vote_count); // etc.
}

// Or you can create a list of all the titles from the rootObj using LINQ
List<string> allTitles = rootObj.data.Select(x => x.title).ToList();

I am not sure what you intend to do with the data you get... so not sure how to explain that piece.. but above example should give you an idea on how to iterate through all the products in the data object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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