Home > Enterprise >  How to deserialize specific Json
How to deserialize specific Json

Time:03-31

Hi guys i try to deserialize a json but this result null , posible its so simple but i cant resolve now , i try this forms, and i use Newtonsoft

if (response.Content.Contains("error"))
{
    JObject jObject = JObject.Parse(response.Content);
    dynamic x = JsonConvert.DeserializeObject<Error>(response.Content);
    error = JsonConvert.DeserializeObject<Error>(response.Content);
    JArray recibos = (JArray)jObject["error"];
    return error;
}

this its the json my response.content

"{\"error\":{\"code\":-10,\"message\":{\"lang\":\"en-us\",\"value\":\"The warehouse is not defined for the item.  [OWOR.Warehouse]\"}}}"

and my class

public class Error
{
    public int code { get; set; }
    public Message message { get; set; }

    public class Message
    {
        public string lang { get; set; }
        public string value { get; set; }
    }
}

CodePudding user response:

try this


if (response.Content != null)
{            {
Data    data = JsonConvert.DeserializeObject<Data>(response.Content);
}

and add class Data (you can change name)

public class Data
{
    public  Error error {get; set;}
}

CodePudding user response:

Your Model class is incorrect to which you are trying to de-serialize your JSON string. Change your Model classes to:

public class Message
{
    public string lang { get; set; }
    public string value { get; set; }
}

public class Error
{
    public int code { get; set; }
    public Message message { get; set; }
}

public class Root
{
    public Error error { get; set; }
}

And your de-serialization will be:

if(string.IsNotNullOrEmpty(response.Content)
{
    if (response.Content.Contains("error"))
    {
        var error = JsonConvert.DeserializeObject<Root>(response.Content);
        return error;
    }   
}

Your error variable will contain the contents of the deserialized result and you can access the required data.

Example working with your JSON string: https://dotnetfiddle.net/NZuwtl

  • Related