Deserializing JToken content to an Object
Asked Answered
T

2

61

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());
Tice answered 13/2, 2015 at 3:41 Comment(0)
S
120

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.

Shotton answered 13/2, 2015 at 4:58 Comment(13)
I used that, something like this List<User> userList = users.ToObject<List<User>>(); however it gives me an error, Error converting value .Tice
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.Shotton
I tried it now and it works. How are you invoking the API? Can you share the code you use for invocation?Shotton
see my updated question. However I'm not testing it by calling the API, I created a console project to test the deserialization.Tice
which one did you try the List or as Array?Tice
I tried the Array version. I did the testing using Fiddler.Shotton
could you try the List, it really gives me an error.Tice
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.Tice
No, a different client should not make any difference. I have updated the answer with the client and server code I used for testing.Shotton
this is funny, it's working in api invocation. :D thanks for the effort @SarathyTice
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)?Enantiomorph
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.Shotton
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;Proscenium
H
2

--This worked for me, the Json is super huge +111000 lines---

//String of keys to search deepin the Json for the desired objects
public string sTokenKeys = "results.drug.drugsfda.partitions";

//Read the download.json file into its objects.                
StreamReader reader = new StreamReader(JsonFileLocation);
var json = reader.ReadToEnd();
var data = JObject.Parse(json);   //Get a JObject from the Json
// Find the desired tree branch by the token keys
var partitionsJObject = data.SelectToken(sTokenKeys).ToList();
// get the array of JTokens and serialize-deserialize into 
// appropriate object 
var partitions = JsonConvert.DeserializeObject<List<Partition>>(JsonConvert.SerializeObject(partitionsJObject));

//now i can read the List<Partition>> partitions object for the 
// values im looking for
Holoenzyme answered 16/10, 2023 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.