Home > Software engineering >  Deserialize JSON with empty attribute name
Deserialize JSON with empty attribute name

Time:10-16

How can I DeserializeObject the following JSON string to a C# object

{"":["Waybill already exist"]}

In some instances the "" can contain a value as well

Like

{"RecevierAddress1" : ["Receiver address 1 can not be blank]}

CodePudding user response:

Whereas what You ask is not possible in principle, because an object property must have a name, what you can do is convert it to a .net JsonDocument which can have properties of zero length string naming.

I presume RL data cause for you to have to handle this, which of cause indicates poor data quality besides that, but You should be able to process it using this technique, here from a unit test

    [Fact]
    public void SerializeSillyObjectJsonTest()
    {
        string serialized = "{\"\":[\"Waybill already exist\"]}";
        var jdoc = System.Text.Json.JsonDocument.Parse(serialized);
        Assert.NotNull(jdoc);

        var jsonElement = jdoc.RootElement.GetProperty("");
        Assert.Equal(1, jsonElement.GetArrayLength());
    }

So You see you can also check on if your property with said name exist and choose what to look for

jdoc.RootElement.TryGetProperty("RecevierAddress1", out var receiverAddressElement)

CodePudding user response:

You can use JsonProperty("") to set the property name to an empty string

class root
{
    [JsonProperty("")]
    public string[] x;  
}
JsonConvert.DeserializeObject<root>(@"{"""":[""Waybill already exist""]}")

For dynamic names, you can either have two properties, or deserialize to a dictionary

JsonConvert.DeserializeObject<Dictionary<string, string[]>>(@"{"""":[""Waybill already exist""]}")
  • Related