Using JsonConvert.DeserializeObject

KevinMcCarthyKevinMcCarthy USMember ✭✭

Tagged:

Answers

  • Adeel984Adeel984 Member ✭✭
    edited January 24

    Make a class

    using System.Runtime.Serialization;
    
    [DataContract]
    class ServerRespose {
    
    [DataMember(Name="AuthResponse", EmitDefaultValue=false)]
     public bool AuthResponse { get; set; }
    
    [DataMember(Name="months", EmitDefaultValue=false)]
     public int ContactID { get; set; }
    
    }
    
    

    Code For deserialization

     public static T Deserialize<T>(string json)
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
    

    Now get Respose & cast it to class

     var obj =  Deserialize<ServerRespose>(response);
    
    
  • KevinMcCarthyKevinMcCarthy USMember ✭✭

    @Adeel984

    Newtonsoft.Json.JsonSerializationException: 'Error converting value "{"AuthResponse":true,"ContactID":9999}" to type 'USM.Model'. Path ''

    Yet if I hard code the JSON string in, it deserializes it fine! It's like Xamarin doesn't like my JSON!
    I have tested my JSON response from POSTMAN to the online testing tools.

    Thanks in advanced!

  • tareqelzoubitareqelzoubi Member ✭✭

    could u please show me you JSON response body

  • soufianemarlysoufianemarly Member ✭✭
    edited February 11

    try this it works

                var answer = httpClient.GetAsync(URL).Result;
                answer.EnsureSuccessStatusCode();
                var lienyear = await answer.Content.ReadAsStringAsync();
                JObject result = JObject.Parse(lienyear);
        Console.WriteLine("result "+ result);
    

    Can you share your JSON Response if the problem still occur :smile:

Sign In or Register to comment.