Horcrux7
Horcrux7

Reputation: 24457

How to convert dynamically in C# the parsed JSON result from Json.NET?

I have implemented a JSON-RPC with Json.NET. The result of the response I convert with:

T data = ((JToken)value).ToObject<T>();

This work if the result is an object. But it does not work if the result is an primitive like Int64 or an string. Then the value is not a JToken.

I have found the method:

static object Convert(object initialValue, CultureInfo culture, Type targetType)

which seems to do the needed job. But the class ConvertUtils is internal. It there any public method to convert any parsed JSON result to any target type?

A more completely sample with the JSON-RPC handling:

JsonRpcResult result = serializer.Deserialize<JsonRpcResult>(jsonTextReader);
Type type = requests[result.id];
object value = result.result;
return ((JToken)value).ToObject(type);

A typical JSON string:

{"jsonrpc":"2.0","result":DynamicValidJsonDependsOnID,"id":1}

The JSON content of DynamicValidJsonDependsOnID depends on the id and can be any valid JSON. There are no limits.

The class JsonRpcResult:

[JsonObject(MemberSerialization.Fields)]
internal class JsonRpcResult
{
    private string jsonrpc;
    private object result;
    private Dictionary<String,Object> error;
    private object id;
 }

Upvotes: 1

Views: 1203

Answers (3)

George Chondrompilas
George Chondrompilas

Reputation: 3247

When you deserialize your JsonRpcResult object, your object result field will either be a complex object or a primitive type.

So if it's a primitive type (ex. Int32), result.result will contain the direct value instead of a JToken

So, I would first check if the Type is primitive or not like this:

JsonRpcResult result = serializer.Deserialize<JsonRpcResult>(jsonTextReader);
Type type = requests[result.id];
object value = result.result;

if (!type.IsPrimitive && type != typeof(decimal) && type != typeof(string) && type != typeof(DateTime))
    return ((JToken)value).ToObject(type);
return value; //otherwise return the value as it is without parsing.

EDIT

As you are getting the Types on runtime, you can't cast the your objects to the correct Type as it is. You have to use the dynamic keyword as mentioned in other answers too, or check if the object's Type is the type you want and cast it like this:

if (type == typeof(string))
{
    string str = (string)returnedValue;
    ...
}

Upvotes: 2

Stoyan Bonchev
Stoyan Bonchev

Reputation: 537

You can use the keyword "dynamic" instead of hard-coded type, so it will resole the type for you. Please take a look at this tutorial:

tutorial

Upvotes: 0

Iswar
Iswar

Reputation: 2301

How about using Newtonsoft.Json.Jobject.Parse like this

 //==== Create class for your Json attributes
 string jsonData= " { \"Employee":{\"name\":\"John\", \"age\":31, \"city\":\"New York\" }}";
 YourJsonClass obj= new YourJsonClass();
 var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonData);
 obj= jObject["Employee"].ToObject<YourJsonClass>();

Your YourJsonClass would be

 public class YourJsonClass
 {
    public string name{ get; set; }
    public int age { get; set; }
    public string city{ get; set; }
 }

You can access through obj like this:

 string name =obj.name;
 int age=obj.age;
 string city=obj.city;

Hope it helps you.

Upvotes: 0

Related Questions