Deserialize a nested json

sdnd2000 41 Reputation points
2021-04-25T20:29:46.543+00:00

I was trying to deserialize nested json, however I got the below error, please advise,

Exception: Newtonsoft.Json.JsonReaderException: After parsing a value an unexpected character was encountered: {. Path 'ShppingAddress[0]', line 14, position 2.

 static void Main(string[] args)
        {
            string json = @"{
 'firstname':'test',
 'lastname':'test',

 'ShppingAddress':
 [
 {
 'ont_addressline1':'1',
 'ont_addressline2':'',
 'ont_city':'1',
 'ont_province':'',
 'ont_postalcode':''
 }
 {
 'ont_addressline1':'2',
 'ont_addressline2':'',
 'ont_city':'2',
 'ont_province':'',
 'ont_postalcode':''
 }
 ],

}";
            Console.WriteLine(json);
            ShippingInfo shippingInfo = JsonConvert.DeserializeObject<ShippingInfo>(json);
            Console.WriteLine("success");
        }

        public class ShippingInfo
        {
            public string firstname { get; set; }
            public string lastname { get; set; }
            public address address { get; set; }
        }

        public class address
        {
            public string ont_addressline1 { get; set; }
            public string ont_addressline2 { get; set; }

            public string ont_city { get; set; }
            public string ont_province { get; set; }
            public string ont_postalcode { get; set; }
        }
    }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,302 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2021-04-25T21:17:24.187+00:00

    See if the following would suit your needs.

    See full source in one of my GitHub repositories done in Visual Studio 2019, C#8. Make sure to read the readme.md file.

    Edit
    I added another code sample that actually does a nested property (thought I had before), updated the repository. So the original below has this too.

    private void SerializeShipInfoListNestedButton_Click(object sender, EventArgs e)  
    {  
        var fileName = "ShipListNested.json";  
      
        var (success, createException) = Mockups.ShippingInfoNestedList().ModelToJson(fileName);  
        if (success)  
        {  
            var (shippingInfos, readException) = Helpers.JsonToListModel<ShippingInfo>(fileName);  
            if (readException == null)  
            {  
                foreach (var shippingInfo in shippingInfos)  
                {  
                    Console.WriteLine($"{shippingInfo.ToString()}");  
                    foreach (var somethingNested in shippingInfo.SomethingNested)  
                    {  
                        Console.WriteLine($@" {somethingNested.Id}, {somethingNested.Value}");  
                    }  
      
                    Console.WriteLine();  
                }  
                  
            }  
            else  
            {  
                MessageBox.Show(readException.Message);  
            }  
      
        }  
        else  
        {  
            MessageBox.Show(createException.Message);  
        }  
    }  
    

    Original.

    using System;  
    using System.Text;  
    using System.Windows.Forms;  
    using JsonCodeSamples.Classes;  
    using JsonCodeSamples.Models;  
      
    namespace JsonCodeSamples  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            private void SerializeShipInfoButton_Click(object sender, EventArgs e)  
            {  
                var fileName = "Ship1.json";  
                  
                var (success, createException) = Mockups.singleShipInfo().ModelToJson(fileName);  
                if (success)  
                {  
                    var (shippingInfo, readException) = Helpers.JsonToModel<ShippingInfo>(fileName);  
                    MessageBox.Show(readException == null ? shippingInfo.ToString() : readException.Message);  
                }  
                else  
                {  
                    MessageBox.Show(createException.Message);  
                }  
            }  
      
            private void SerializeShipInfoListButton_Click(object sender, EventArgs e)  
            {  
                var fileName = "ShipList.json";  
                  
                var (success, createException) = Mockups.ShippingInfoList().ModelToJson(fileName);  
                if (success)  
                {  
                    var (shippingInfos, readException) = Helpers.JsonToListModel<ShippingInfo>(fileName);  
                    if (readException == null)  
                    {  
                        var sb = new StringBuilder();  
                        shippingInfos.ForEach(item => sb.AppendLine(item.ToString()));  
                        MessageBox.Show(sb.ToString());  
                    }  
                      
                }  
                else  
                {  
                    MessageBox.Show(createException.Message);  
                }  
      
            }  
        }  
    }  
    

    single instance json

    {  
      "AddressDetails": {  
        "Street": "1 Maple Drive",  
        "City": "Portland",  
        "State": "OR",  
        "PostalCode": "97666"  
      },  
      "FirstName": "Jim",  
      "LastName": "Adams",  
      "Gender": 0  
    }  
    

    list json

    [  
      {  
        "AddressDetails": {  
          "Street": "1 Maple Drive",  
          "City": "Portland",  
          "State": "OR",  
          "PostalCode": "97666"  
        },  
        "FirstName": "Jim",  
        "LastName": "Adams",  
        "Gender": 0  
      },  
      {  
        "AddressDetails": {  
          "Street": "1 Maple Drive",  
          "City": "Portland",  
          "State": "OR",  
          "PostalCode": "97666"  
        },  
        "FirstName": "Mary",  
        "LastName": "Adams",  
        "Gender": 1  
      }  
    ]  
    

    ---
    90979-kpmvp1.png

    1 person found this answer helpful.
    0 comments No comments

  2. Timon Yang-MSFT 9,576 Reputation points
    2021-04-26T02:22:05.213+00:00

    As the exception message says, your Json string has a format error. Please add a comma between the two objects.

              ......  
              'ont_province':'',  
              'ont_postalcode':''  
            },  
            {  
               'ont_addressline1':'2',  
               'ont_addressline2':'',  
               'ont_city':'2',  
               ......  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments