0

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]}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • 1
    Does this answer your question? [How to Convert JSON object to Custom C# object?](https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object) – Leo Oct 15 '21 at 11:55
  • You can't have properties without names, so you can't deserialize this JSON into a simple C# object. You can deserialize it into a `Dictionary` though – Panagiotis Kanavos Oct 15 '21 at 11:56
  • @Leo the question is how to deserialize a string with an empty name – Panagiotis Kanavos Oct 15 '21 at 11:57
  • What are you expecting this to deserialise to? – the.Doc Oct 15 '21 at 12:05
  • sounds like you are trying to validate some post on the backend, why not you send the json response with: `{ "error": "Waybill already exists" }` and `{ "error": "receiver address 1 cannot be blank", "field": "ReceiverAddress1" }`? – Leo Oct 15 '21 at 12:15

2 Answers2

1

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)
T. Nielsen
  • 835
  • 5
  • 18
  • 1
    Another way to read this json is using the `JsonDocument.RootElement.EnumerateObject` method to get Name and Value of each property – Leo Oct 15 '21 at 12:12
1

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""]}")
Charlieface
  • 52,284
  • 6
  • 19
  • 43