none
How to use System.Text.Json to write a Json object having a nested Json array? RRS feed

  • Question

  • Hello,
    Today, I upgrade my IDE from Visual Studio 2019 Version 16.3.0 to 16.3.1 on Windows 10 (Version 1903).
    I want to try some new stuff, like System.text.json, if succeed, I can get rid of Newtonsoft.json.
    I know how to write a simple Json Object with Utf8JsonWriter, but I have some data having nested Json array.  
    Like the following Json data:
    {
        "account_id": "1234567890",
        "rate": 1.0,
        "balance": ["GBP", 10000.0],
        "account_open": true
    }
    For the json key/value: "balance": ["GBP", 10000.0], it is a Json array, but I have no idea on how to write this Json array using Utf8JsonWriter.
    I have tried the following C# code:

    using var stream = new MemoryStream();
    using (var writer0 = new Utf8JsonWriter(stream, options))
    {
        writer0.WriteStartArray();
        writer0.WriteString("GBP", "10000.0");
        writer0.WriteEndArray();
    }
    string json0 = Encoding.UTF8.GetString(stream.ToArray());
    Console.WriteLine(json0);
    

    But I got run time error:
    Message=Cannot write a JSON property within an array or as the first JSON token. Current token type is 'StartArray'.
    Any idea on how to do the job? I want to write the complete Json object including Json array inside.
    Thanks,

    Wednesday, September 25, 2019 8:32 PM

Answers

  • Hi zydjohn,

    Thank you for posting here.

    I think you could use json.serilize to write a Json object having a nested Json array.

    You could try the following code.

    class Program
        {
            static void Main(string[] args)
            {
                Example ex = new Example() { AccountId = 123456, Rate = 1.0, balance = new List<object> { "GBP", 10000.0 } , Account_Open=true};
                string json = JsonSerializer.Serialize<Example>(ex);
                Console.WriteLine(json);
                Console.ReadKey();
            }
    
    
    
        }
    
        public class Example
        { 
         public int AccountId { get; set; }
         public double Rate { get; set; }
         public List<object> balance { get; set; }
    
         public bool Account_Open { get; set; }
        
        
        }

    Result:

    Best Regards,

    Jack


    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 zydjohn Thursday, September 26, 2019 12:19 PM
    Thursday, September 26, 2019 7:19 AM
    Moderator

All replies

  • I think you have to call writer0.WriteStartObject() as the first call to use this.

    When done, call .WriteEndObject() to close it.

    writer0.WriteStartObject(); writer0.WriteString("account_id", "1234567890"); writer0.WriteNumber("rate", 1); writer0.WriteStartArray("balance");
    //note: I break it into 2 lines because they're seperated by comma.
    //If you mean ["GBP":10000] then it is WriteNumber("GBP", 10000) writer0.WriteStringValue("GBP"); writer0.WriteNumberValue(10000); writer0.WriteEndArray(); writer0.WriteBoolean("account_open", true); writer0.WriteEndObject();

    Since .WriteNumber() uses "G"(i.e.: General) format automatically, and the JsonWriterOptions does not have option for numeric formatting for you, I don't think it's possible to write the value as "1.0" there.

    The simple usage rule is, if you need to add object/array, you start with .WriteStart*() and end with .WriteEnd*(). Both kind of start method supports adding property name with it.

    For values, call .Write*() if you need to write both property/key and value, and .Write*Value() if you only need to write value.


    Thursday, September 26, 2019 1:36 AM
    Answerer
  • Hi zydjohn,

    Thank you for posting here.

    I think you could use json.serilize to write a Json object having a nested Json array.

    You could try the following code.

    class Program
        {
            static void Main(string[] args)
            {
                Example ex = new Example() { AccountId = 123456, Rate = 1.0, balance = new List<object> { "GBP", 10000.0 } , Account_Open=true};
                string json = JsonSerializer.Serialize<Example>(ex);
                Console.WriteLine(json);
                Console.ReadKey();
            }
    
    
    
        }
    
        public class Example
        { 
         public int AccountId { get; set; }
         public double Rate { get; set; }
         public List<object> balance { get; set; }
    
         public bool Account_Open { get; set; }
        
        
        }

    Result:

    Best Regards,

    Jack


    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 zydjohn Thursday, September 26, 2019 12:19 PM
    Thursday, September 26, 2019 7:19 AM
    Moderator