C# 将 JSON DynamicObject 分配给 Class

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;
    ...
}

行:

RootObject RO = (RootObject)jObject;

不正确。如何将 DynamicObject 分配给我的 Class?

您不能将 DynamicObject 分配给类型为 RootObject 的变量,因为类型不是 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);

有关如何反序列化为特定类型的更多示例,另请参阅 How can I parse JSON with C#? and How to Convert JSON object to Custom C# object?