Deserialization of a Facebook JSON string?

こ雲淡風輕ζ 提交于 2019-12-04 19:22:40

You need to use correct property names that match your JSON structure:

using System;
using Newtonsoft.Json;

public class Data
{
    public CurrentLocation current_location { get; set; }
    public WorkHistory[] work_history { get; set; }
    public EducationHistory[] education_history { get; set; }
}

public class EducationHistory
{
    public string name { get; set; }
    public int? year { get; set; }
    public string school_type { get; set; }
}

public class WorkHistory
{
    public string company_name { get; set; }
    public Location location { get; set; }
}

public class CurrentLocation
{
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set; }
}

public class Location
{
    public string city { get; set; }
    public string state { get; set; }
}

class Program
{
    static void Main()
    {
        var json = 
        @"
        {
            ""current_location"": {
                ""city"": ""Delhi"",
                ""state"": ""Delhi"",
                ""country"": ""India"",
                ""zip"": """",
                ""id"": 102161913158207,
                ""name"": ""Delhi, India""
            },
            ""education_history"": [
                {
                    ""name"": ""I E T , Alwar (Raj.)"",
                    ""year"": 2007,
                    ""concentrations"": [],
                    ""school_type"": ""College""
                },
                {
                    ""name"": ""Institute of Engineering and Technology, Alwar"",
                    ""concentrations"": [],
                    ""school_type"": ""College""
                }
            ],
            ""work_history"": [
                {
                    ""location"": {
                        ""city"": """",
                        ""state"": """"
                    },
                    ""company_name"": ""Defence Research & Development Organisation (DRDO)"",
                    ""description"": """",
                    ""start_date"": ""0000-00"",
                    ""end_date"": ""0000-00""
                }
            ]
        }";

        Data soap = JsonConvert.DeserializeObject<Data>(json);
        Console.WriteLine(soap.current_location.city);
    }
}

As far as the affiliations property is concerned, I don't see any relation to it with your JSON, so I simply removed it from the Data object and replaced it with the EducationHistory type.


UPDATE:

And to handle multiple nodes you could adapt your models:

public class Result
{
    public Data[] data { get; set; }
}

public class Data
{
    public CurrentLocation current_location { get; set; }
    public WorkHistory[] work_history { get; set; }
    public EducationHistory[] education_history { get; set; }
}

public class EducationHistory
{
    public string name { get; set; }
    public int? year { get; set; }
    public string school_type { get; set; }
}

public class WorkHistory
{
    public string company_name { get; set; }
    public Location location { get; set; }
}

public class CurrentLocation
{
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set; }
}

public class Location
{
    public string city { get; set; }
    public string state { get; set; }
}

and then:

Result soap = JsonConvert.DeserializeObject<Result>(json);
Console.WriteLine(soap.data[0].current_location.city);

Instead of declaring a lot of tiny classes I would go dynamic way. Here is the code for dynamic json object. And the usage would be something like this:

dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(jsonString);

Console.WriteLine("{0} , {1}", obj.current_location.city, obj.current_location.state);

Console.WriteLine("EDUCATION");
foreach (var eduHist in obj.education_history)
{
    Console.WriteLine("{0} , {1}", eduHist.name, eduHist.year);
}

Console.WriteLine("WORK");
foreach (var workHist in obj.work_history)
{
    Console.WriteLine("{0}  {1}-{2}", workHist.company_name, workHist.start_date, workHist.end_date);
}

Here's another example that's working for retrieving id, name, picture and friends. You must include reference to newtonsoft.json package.

[TestClass]
public class FbRequestParserTests
{
    [TestMethod]
    public void ParseFacebookResponse()
    {
        var response =
            @"{
              ""id"": ""123123"",
              ""name"": ""My name"",
              ""picture"": {
                            ""data"": {
                                ""is_silhouette"": false,
                                ""url"": ""https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/14572785_123""
                            }
                        },
              ""friends"": {
                ""data"": [
                    {
                    ""name"": ""Friend 1"",
                    ""id"": ""123""
                  },
                  {
                    ""name"": ""Friend 2"",
                    ""id"": ""234""
                  }
                ],
                ""paging"": {
                  ""cursors"": {
                    ""before"": ""QVFIUk1yRE9zTkhFdkc1TFV2SHVpaE1IYUJ4V2ljbUJSbjYxaGhnX05IcTNYWHp0ekNHZAnh6LThs"",
                    ""after"": ""QVFIUjFFQW5kVmJiTmMxZAHN6cWNDdUl5VnVJVl91UG0yV2hMOVl5N21GTDVxQ2JVQ2hjQVlRYXBxNDNkWWI3YjZAkZAFBV""
                  }
                },
                ""summary"": {
                  ""total_count"": 456
                }
              }
            }";

        var result = JsonConvert.DeserializeObject<FbResponse>(response);

        Assert.AreEqual(result.Id, 123123);
        Assert.AreEqual(result.Name, "My Name");
    }
}

public class FbResponse
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Picture Picture { get; set; }
    public Friends Friends { get; set; }
}
public class Friends
{
    public List<FriendsData> Data { get; set; }
    public Paging Paging { get; set; }
    public Summary Summary { get; set; }
}
public class Summary
{
    public int Total_Count { get; set; }
}
public class Paging
{
    public Cursors Cursors { get; set; }
}
public class Cursors
{
    public string Before { get; set; }
    public string After { get; set; }
}
public class FriendsData
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Picture
{
    public PictureData Data { get; set; }
}
public class PictureData
{
    public bool Is_Silhouette { get; set; }
    public string Url { get; set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!