Remove double curly brackets from JObject that have been added during deserialization

后端 未结 2 1983
谎友^
谎友^ 2020-12-18 17:51

I have a JSON string that starts and ends with curly brackets \"{}\".

I then deserialize the object but when this is done I see that I now have double curly brackets

相关标签:
2条回答
  • 2020-12-18 18:29

    In my case I want

    "object" : {
            [
                {"a"="b"},
                {"a"="b"},
                {"a"="b"},
                [
                    {"a"="b"},
                    {"a"="b"}
                ]
            ]
        }
    
    To
    
    "object" : {
            [
                {"a"="b"},
                {"a"="b"},
                {"a"="b"},
                {"a"="b"},
                {"a"="b"}
            ]
        }
    

    So Simple I using foreach like this

    alpha =  @"[{'a'='b'},{'a'='b'}]";
    JArray arrayObject = JArray.Parse(alpha);
    foreach (var item in arrayObject)
    {
        obj["object"].Last.AddAfterSelf(item);
    }
    
    0 讨论(0)
  • 2020-12-18 18:36

    Is this causing a problem or are you just curious? I had the same issue when I was sending data as the type "object" inside another a container class. The container itself was being deserialized properly but the object inside wasn't. I thought it wasn't deserializing it because of the double curly braces. In reality, it seems that may just be how JObjects look. The real reason was probably because I had turned off the setting where it sent the type information and since I was deserializing to "object" it couldn't possibly know what the type from a string alone.

    Either way, I noticed if you did ".ToString()" on it then the double curly braces would disappear. This meant I was able to solve my issue by simply doing:

    var someType = JsonConvert.DeserializeObject<SomeType>(jObject.ToString());
    

    I'm not sure if this is a bug or not but my guess is that it's simply an internal implementation detail and that's why they have it 'fixed' when you ".ToString()".

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