Json.NET (Newtonsoft.Json) - Two 'properties' with same name?

后端 未结 2 1040
广开言路
广开言路 2020-12-02 01:05

I\'m coding in C# for the .NET Framework 3.5.

I am trying to parse some Json to a JObject.

The Json is as follows:

{
    \"TBox\": {
                 


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 01:28

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    JsonTextReader jsonReader = new JsonTextReader(reader);
    jsonReader.Read();
    while(jsonReader.Read())
    {
        if(jsonReader.TokenType == JsonToken.StartObject)
        {
            JObject tbox = JObject.Load(jsonReader);
        }
    }
    

    However, note that the RFC says, "The names within an object SHOULD be unique" so if you can, recommend the format be changed.

    EDIT: Here's an alternate design that doesn't have duplicate keys:

    [
        {
            "TBox": {
                "Width": 1,
                "Length": 1,
                "Name": "SmallBox",
                "Height": 2
            }
        },
        {
            "TBox": {
                "Width": 10,
                "Length": 5,
                "Name": "MedBox",
                "Height": 10
            }
        },
        {
            "TBox": {
                "Width": 20,
                "Length": 20,
                "Name": "LargeBox",
                "Height": 10
            }
        }
    ]
    

提交回复
热议问题