user2272143 user2272143 - 4 months ago 20
JSON Question

C# Assign JSON DynamicObject to a Class

public class RootObject
{
public List<Result> results { get; set; }
public int result_index { get; set; }
}


...

private void ReadJson()
{
string JsonString = File.ReadAllText(MyJsonFile);
DynamicObject jObject = System.Web.Helpers.Json.Decode(JsonString);
RootObject RO = (RootObject)jObject;
...
}


The line:

RootObject RO = (RootObject)jObject;


is not correct. How is possible to assign the DynamicObject to my Class?

dbc dbc
Answer

You cannot assign a DynamicObject to a variable of type RootObject because the types are not assignable. Instead, you should deserialize your JSON as a RootObject to begin with using Json.Decode<T>:

var RO = System.Web.Helpers.Json.Decode<RootObject>(JsonString);

See also How can I parse JSON with C#? and How to Convert JSON object to Custom C# object? for more examples of how to deserialize to a specific type.