-1

I have a json string like this: {"status":false,"data":{"errors":{"":"error45"}}}

I cant make a class for this json string, because the last part has no name => ""

I test this class:

public class Result
{
    public bool status { set; get; }
    public ResultDetail data { set; get; }
}

public class ResultDetail
{
    public ErrorDetails errors { set; get; }       
}

public class ErrorDetails
{        
    public string abc { set; get; }
}

but abc returns null !!!!

1 Answers1

1

You can use the Dictionary<string, string> for the errors.

public class Result
{
    public bool status { set; get; }
    public ResultDetail data { set; get; }
}

public class ResultDetail
{
    public Dictionary<string, string> errors { set; get; }
}

and use the following to deserialize and access the dictionary.

var result = JsonConvert.DeserializeObject<Result>(json);
Console.WriteLine(result.data.errors.Values.FirstOrDefault());

Or you can assign the value to a variable

obj.data.errors.TryGetValue("", out string error);
Console.WriteLine(error);

I will mention this as well that the property names should be Proper names (first letter Capital). To be able to deserialize properly, use the [JsonProperty("corresponding_json_key")] to each of your properties of your classes to conform to C# standards.

public class Result
{
    [JsonProperty("status")]
    public bool Status { set; get; }

    [JsonProperty("data")]
    public ResultDetail Data { set; get; }
}
Jawad
  • 11,028
  • 3
  • 24
  • 37