none
Deserialize complex Json in C# RRS feed

  • Question

  • Goal:
    Deserialize Json in C# and retrieve data "Slåttsveavegen 104, 2412 Sørskogbygda, Norway"

    Problem:
    I don't know how to retrieve the data. What part of the source code am I missing?

    Info:
    *http://jsoneditoronline.org/?id=1f8261c710bf32624f1c5fe042694e24

    Thank you!

    My code:

    string json2 = "";
    
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json2)))
    {
        // Deserialization from JSON  
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite2));
        BlogSite2 bsObj2 = (BlogSite2) deserializer.ReadObject(ms);
    
        int fff = 23;
    }

    [DataContract]
    public class BlogSite2
    {
        [DataMember]
        public string authenticationResultCode { get; set; }
    
        [DataMember]
        public string brandLogoUri { get; set; }
    
        [DataMember]
        public string adminDistrict2 { get; set; }
    
        [DataMember]
        public List<resourceSets> resourceSetss { get; set; }
    
    }
    
    
    [DataContract]
    public class resourceSets
    {
    
        public resourceSets()
        {
            resourcess = new List<resources>();
        }
    
    
        [DataMember]
        public int estimatedTotal { get; set; }
    
        [DataMember]
        public List<resources> resourcess { get; set; }
    }
    
    
    [DataContract]
    public class resources
    {
        [DataMember]
        public string name { get; set; }
    
        [DataMember]
        public string entityType { get; set; }
    }

    Json code:

    {
      "authenticationResultCode": "ValidCredentials",
      "brandLogoUri": "http://dev.virtualearth.net/Branding/logo_powered_by.png",
      "copyright": "Copyright © 2017 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
      "resourceSets": [
        {
          "estimatedTotal": 1,
          "resources": [
            {
              "__type": "Location:http://schemas.microsoft.com/search/local/ws/rest/v1",
              "bbox": [
                60.9504958,
                11.7680448,
                60.9527442,
                11.7726752
              ],
              "name": "Slåttsveavegen 104, 2412 Sørskogbygda, Norway",
              "point": {
                "type": "Point",
                "coordinates": [
                  60.95162,
                  11.77036
                ]
              },
              "address": {
                "addressLine": "Slåttsveavegen 104",
                "adminDistrict": "Hedmark",
                "adminDistrict2": "Elverum",
                "countryRegion": "Norway",
                "formattedAddress": "Slåttsveavegen 104, 2412 Sørskogbygda, Norway",
                "locality": "Sørskogbygda",
                "postalCode": "2412"
              },
              "confidence": "High",
              "entityType": "Address",
              "geocodePoints": [
                {
                  "type": "Point",
                  "coordinates": [
                    60.95162,
                    11.77036
                  ],
                  "calculationMethod": "Rooftop",
                  "usageTypes": [
                    "Display"
                  ]
                },
                {
                  "type": "Point",
                  "coordinates": [
                    60.95163,
                    11.7706
                  ],
                  "calculationMethod": "Rooftop",
                  "usageTypes": [
                    "Route"
                  ]
                }
              ],
              "matchCodes": [
                "Good"
              ]
            }
          ]
        }
      ],
      "statusCode": 200,
      "statusDescription": "OK",
      "traceId": "549a65398db847b992096e20748c5734|DB40120742|7.7.0.0|"
    }

    Wednesday, December 13, 2017 7:40 PM

Answers

  • Hello Sakura,

    Your class structure doesn't match your Json format and this is main cause of the exception. You could get quickly fixed in Visual studio.

    Copy json string>>Click "Edit" >>Chose "Paste Special">>Select "Paste Json As Class" and you will get the correct structure as below.

      [DataContract]
        public class Rootobject
        {
            public string authenticationResultCode { get; set; }
            public string brandLogoUri { get; set; }
            public string copyright { get; set; }
            [DataMember]
            public Resourceset[] resourceSets { get; set; }
            public int statusCode { get; set; }
            public string statusDescription { get; set; }
            public string traceId { get; set; }
        }
        [DataContract]
        public class Resourceset
        {
            [DataMember]
            public int estimatedTotal { get; set; }
            [DataMember]
            public Resource[] resources { get; set; }
        }
        [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1", Name = "Location")]
        public class Resource
        {
            public string __type { get; set; }
            public float[] bbox { get; set; }
            [DataMember]
            public string name { get; set; }
            public Point point { get; set; }
            public Address address { get; set; }
            public string confidence { get; set; }
            public string entityType { get; set; }
            public Geocodepoint[] geocodePoints { get; set; }
            public string[] matchCodes { get; set; }
        }
    
        public class Point
        {
            public string type { get; set; }
            public float[] coordinates { get; set; }
        }
    
        public class Address
        {
            public string addressLine { get; set; }
            public string adminDistrict { get; set; }
            public string adminDistrict2 { get; set; }
            public string countryRegion { get; set; }
            public string formattedAddress { get; set; }
            public string locality { get; set; }
            public string postalCode { get; set; }
        }
    
        public class Geocodepoint
        {
            public string type { get; set; }
            public float[] coordinates { get; set; }
            public string calculationMethod { get; set; }
            public string[] usageTypes { get; set; }
        }

    The only thing you should pay attention is "_Type" element, it has some special meaning for DataContractJsonSerializer.

    https://stackoverflow.com/questions/4115037/problem-with-deserializing-json-on-datamember-type

    Test code

     string json2 = File.ReadAllText("json1.json");
    
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json2)))
                {
                    // Deserialization from JSON  
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Rootobject));
    
                    Rootobject bsObj2 = (Rootobject)deserializer.ReadObject(ms);
    
                    Console.WriteLine(bsObj2.resourceSets[0].resources[0].name);
                }
                Console.Read();

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Sakura Data Thursday, December 14, 2017 9:05 AM
    Thursday, December 14, 2017 7:07 AM
    Moderator

All replies

  • Hello Sakura,

    Your class structure doesn't match your Json format and this is main cause of the exception. You could get quickly fixed in Visual studio.

    Copy json string>>Click "Edit" >>Chose "Paste Special">>Select "Paste Json As Class" and you will get the correct structure as below.

      [DataContract]
        public class Rootobject
        {
            public string authenticationResultCode { get; set; }
            public string brandLogoUri { get; set; }
            public string copyright { get; set; }
            [DataMember]
            public Resourceset[] resourceSets { get; set; }
            public int statusCode { get; set; }
            public string statusDescription { get; set; }
            public string traceId { get; set; }
        }
        [DataContract]
        public class Resourceset
        {
            [DataMember]
            public int estimatedTotal { get; set; }
            [DataMember]
            public Resource[] resources { get; set; }
        }
        [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1", Name = "Location")]
        public class Resource
        {
            public string __type { get; set; }
            public float[] bbox { get; set; }
            [DataMember]
            public string name { get; set; }
            public Point point { get; set; }
            public Address address { get; set; }
            public string confidence { get; set; }
            public string entityType { get; set; }
            public Geocodepoint[] geocodePoints { get; set; }
            public string[] matchCodes { get; set; }
        }
    
        public class Point
        {
            public string type { get; set; }
            public float[] coordinates { get; set; }
        }
    
        public class Address
        {
            public string addressLine { get; set; }
            public string adminDistrict { get; set; }
            public string adminDistrict2 { get; set; }
            public string countryRegion { get; set; }
            public string formattedAddress { get; set; }
            public string locality { get; set; }
            public string postalCode { get; set; }
        }
    
        public class Geocodepoint
        {
            public string type { get; set; }
            public float[] coordinates { get; set; }
            public string calculationMethod { get; set; }
            public string[] usageTypes { get; set; }
        }

    The only thing you should pay attention is "_Type" element, it has some special meaning for DataContractJsonSerializer.

    https://stackoverflow.com/questions/4115037/problem-with-deserializing-json-on-datamember-type

    Test code

     string json2 = File.ReadAllText("json1.json");
    
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json2)))
                {
                    // Deserialization from JSON  
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Rootobject));
    
                    Rootobject bsObj2 = (Rootobject)deserializer.ReadObject(ms);
    
                    Console.WriteLine(bsObj2.resourceSets[0].resources[0].name);
                }
                Console.Read();

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Sakura Data Thursday, December 14, 2017 9:05 AM
    Thursday, December 14, 2017 7:07 AM
    Moderator
  • Thank you for your help!
    Thursday, December 14, 2017 9:05 AM