user2272143
user2272143

Reputation: 469

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?

Upvotes: 0

Views: 319

Answers (1)

dbc
dbc

Reputation: 116786

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.

Upvotes: 1

Related Questions