57

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());
JJS
  • 6,431
  • 1
  • 54
  • 70
Robert Mansion
  • 577
  • 1
  • 4
  • 10

1 Answers1

112

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.

Parthasarathy
  • 2,698
  • 1
  • 12
  • 14
  • 1
    I used that, something like this `List userList = users.ToObject>();` however it gives me an error, `Error converting value `. – Robert Mansion Feb 13 '15 at 05:29
  • Can you try users.ToObject(). I think JSON.net treats the object as an array. Meanwhile I will try to replicate this in my machine. – Parthasarathy Feb 13 '15 at 06:17
  • I tried it now and it works. How are you invoking the API? Can you share the code you use for invocation? – Parthasarathy Feb 13 '15 at 06:28
  • 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 Feb 13 '15 at 06:49
  • which one did you try the `List` or as `Array`? – Robert Mansion Feb 13 '15 at 06:50
  • I tried the Array version. I did the testing using Fiddler. – Parthasarathy Feb 13 '15 at 06:52
  • could you try the `List`, it really gives me an error. – Robert Mansion Feb 13 '15 at 07:05
  • 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. – Robert Mansion Feb 13 '15 at 07:06
  • No, a different client should not make any difference. I have updated the answer with the client and server code I used for testing. – Parthasarathy Feb 13 '15 at 07:20
  • this is funny, it's working in api invocation. :D thanks for the effort @Sarathy – Robert Mansion Feb 13 '15 at 08:21
  • 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)? – Nick Feb 11 '20 at 17:08
  • I have not tried this yet. But there is an overload for the method ToObject() 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. – Parthasarathy Feb 18 '20 at 06:43
  • ToObject will create new instance and will throw exception for abstract class or interface it's better to convert it using the type var result = JsonConvert.DeserializeObject(myjson.ToString(Formatting.None), ChildClassType) as BaseClassType; – Abdullah Tahan Mar 24 '23 at 14:07