Deserializing JToken content to an Object

63,649

You can use JToken.ToObject generic method. http://www.nudoq.org/#!/Packages/Newtonsoft.Json/Newtonsoft.Json/JToken/M/ToObject(T)

Server API Code:

 public void Test(JToken users)
 {
     var usersArray = users.ToObject<User[]>();
 }

Here is the client code I use.

string json = "[{\"UserId\":0,\"Username\":\"jj.stranger\",\"FirstName\":\"JJ\",\"LastName\":\"stranger\"}]";
HttpClient client = new HttpClient();
var result = client.PostAsync(@"http://localhost:50577/api/values/test", new StringContent(json, Encoding.UTF8, "application/json")).Result;

The object gets converted to Users array without any issues.

Share:
63,649
Robert Mansion
Author by

Robert Mansion

Salesforce and .NET Jr. Developer.

Updated on July 09, 2022

Comments

  • Robert Mansion
    Robert Mansion almost 2 years

    I want to deserialize JToken content to an object (User). How am I able to do this?

    Here is my json string:

    string json = @"[{""UserId"":0,""Username"":""jj.stranger"",""FirstName"":""JJ"",""LastName"":""stranger""}]";
    

    This being sent to an api parameter as JToken.

    User class:

    public class user
    {
        public int UserId {get; set;}
        public string Username {get; set;}
        public string FirstName {get; set;}
        public string LastName {get; set;}
    }
    

    Web Api Method:

    public IHttpActionResult Post([FromBody]JToken users)
    {
          UserModel.SaveUser(users);
          //...
    }
    

    API Invocation in Salesforce:

    string json = '[{"UserId":0,"Username":"jj.stranger","FirstName":"JJ","LastName":"stranger"}]';
    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
                
    req.setEndpoint('test.com/api/UserManagement');
    req.setMethod('POST');
    req.setBody(json);
    req.setHeader('Content-Type', 'application/json');
                
    try {
        res = http.send(req);
    } catch(System.CalloutException e) {
        System.debug('Callout error:' + e);
    }
                
    System.debug(res.getBody());
    
  • Robert Mansion
    Robert Mansion over 9 years
    I used that, something like this List<User> userList = users.ToObject<List<User>>(); however it gives me an error, Error converting value .
  • Parthasarathy
    Parthasarathy over 9 years
    Can you try users.ToObject<User[]>(). I think JSON.net treats the object as an array. Meanwhile I will try to replicate this in my machine.
  • Parthasarathy
    Parthasarathy over 9 years
    I tried it now and it works. How are you invoking the API? Can you share the code you use for invocation?
  • Robert Mansion
    Robert Mansion over 9 years
    see my updated question. However I'm not testing it by calling the API, I created a console project to test the deserialization.
  • Robert Mansion
    Robert Mansion over 9 years
    which one did you try the List or as Array?
  • Parthasarathy
    Parthasarathy over 9 years
    I tried the Array version. I did the testing using Fiddler.
  • Robert Mansion
    Robert Mansion over 9 years
    could you try the List, it really gives me an error.
  • Robert Mansion
    Robert Mansion over 9 years
    It would make any difference If test this in the console project that I created right? hmm, but I will try it in invoking the api.
  • Parthasarathy
    Parthasarathy over 9 years
    No, a different client should not make any difference. I have updated the answer with the client and server code I used for testing.
  • Robert Mansion
    Robert Mansion over 9 years
    this is funny, it's working in api invocation. :D thanks for the effort @Sarathy
  • Robert Mansion
    Robert Mansion over 9 years
    I appreciate your help :)
  • Nick
    Nick over 4 years
    This works fine, but it simply ignores data fields which cannot be mapped to the target class. Is there a way to get errors for that (appreciated with field name)?
  • Parthasarathy
    Parthasarathy about 4 years
    I have not tried this yet. But there is an overload for the method ToObject<T>() which accepts an instance of JsonSerializer. You can try to create an instance of JsonSerializer and set the value of MissingMemberHandling to Error. But this will throw a JsonSerializationException as per the documentation.