skip to Main Content

I have a Windows Forms .NET application and I am writing JSON formatted text to a text file using the Newtonsoft JSON.NET library. I want to write two sets of brackets to denote that points is a list of lists even though it only contains one list (shown below).

{
    "rallyPoints:" {
        "points": [
            [
                0.0,
                1.0,
                2.0
            ]
        ]
    }
}

Here is my code:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;

void exampleFunction()
{
    string filePath = @"path/to/file.json";
    List<List<double>> rallyPoints = new List<List<double>>();
    List<double> singleRallyPoint = new List<double>
    {
        0.0, 1.0, 2.0
    };
    rallyPoints.Add(singleRallyPoint);

    JObject mainObject = new JObject(
        new JProperty("rallyPoints", new JObject(
        new JProperty("points", rallyPoints)
        ))
    );

    using (StreamWriter file = File.CreateText(filePath))
    using (JsonTextWriter writer = new JsonTextWriter(file))
    {
        writer.Formatting = Formatting.Indented;
        mainObject.WriteTo(writer);
    }
}

My code writes to the text file as shown below. Notice that the points field only has one set of brackets rather than two sets so it is not clear that this is a list of lists.

{
    "rallyPoints:" {
        "points": [
            0.0,
            1.0,
            2.0
        ]
    }
}

I am not sure if what I am trying to accomplish is a proper JSON format. Maybe it’s the case that with JSON a list of lists containing only a single list as an element is formatted as a list. I haven’t been able to verify that online thus far. Even if what I am attempting is not proper JSON I would still like to know if there is a solution. Thank you.

2

Answers


  1. Convert the List<List<double>> to JArray should solve the issue.

    JArray.FromObject(rallyPoints)
    
    JObject mainObject = new JObject(
        new JProperty("rallyPoints", 
            new JObject(
                new JProperty("points", JArray.FromObject(rallyPoints))
            )
        )
    );
    
    Login or Signup to reply.
  2. the easiest way is to use an anonymous type

    void exampleFunction()
    {
        string filePath = @"path/to/file.json";
    
        var result = new
        {
            rallyPoinst = new
            {
                points = new List<List<double>> {
                         new List<double> {
                            0.0, 1.0, 2.0
                         }}
            }
        };
    
        var json=JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);
        File.WriteAllText(filePath, json);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search