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

后端 未结 2 1041
广开言路
广开言路 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
            }
        }
    ]
    
    0 讨论(0)
  • 2020-12-02 01:41

    If I'm not mistaken, the correct answer to this is that your input is not actually JSON. So no, getting a JSON parser to parse it probably isn't going to work.

    Maybe you don't have any control over the source of the input, so I'd use a Regex or something to pre-filter the string. Turn it into something like:

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

    And treat it like the array that it is.

    0 讨论(0)
提交回复
热议问题