-1

我有一个 API 调用的结果,如下所示:

{"Operations":[{"OperationId":"2","OperationObjectId":"Application","OperationName":"UnlockSession","OperationParameters":[{"Name":"viewModel","Value":"model"},{"Name":"returnUrl","Value":"https://"}],"OperationCaller":{"UserPrincipalName":"bob","ClientIPAddress":""},"OperationResult":"Succeeded","OperationStatus":200,"OperationRequest":{"Method":"POST","Url":""},"OperationStartedTime":"2013-08-20T12:04:17.5462357Z","OperationCompletedTime":"2013-08-20T12:04:17.9979469Z"}],"ContinuationToken":null}

理想情况下,我想将其转换为对象,以便可以执行以下操作:

object.OperationObjectID; // gives Application
object.Method; // gives POST
object.OperationResult; // gives Succeeded

有谁知道这是怎么做到的?JSON 解析是否需要了解格式?

谢谢,安德鲁

4

2 回答 2

1

你可以使用 Json.Net 如下

dynamic object = JObject.Parse(yorjsonstring);

object.Operations[0].OperationObjectID;
object.Operations[0].Method;
object.Operations[0].OperationResult;

而不是使用动态对象,您可以为您的 json 生成类并序列化到这些类,如下所示。您可以从http://json2csharp.com/站点获得帮助以生成类

public class OperationParameter
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class OperationCaller
{
    public string UserPrincipalName { get; set; }
    public string ClientIPAddress { get; set; }
}

public class OperationRequest
{
    public string Method { get; set; }
    public string Url { get; set; }
}

public class Operation
{
    public string OperationId { get; set; }
    public string OperationObjectId { get; set; }
    public string OperationName { get; set; }
    public List<OperationParameter> OperationParameters { get; set; }
    public OperationCaller OperationCaller { get; set; }
    public string OperationResult { get; set; }
    public int OperationStatus { get; set; }
    public OperationRequest OperationRequest { get; set; }
    public string OperationStartedTime { get; set; }
    public string OperationCompletedTime { get; set; }
}

public class RootObject
{
    public List<Operation> Operations { get; set; }
    public object ContinuationToken { get; set; }
}

然后

RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonstring);
obj.Operations[0].OperationObjectID;
于 2013-08-22T06:40:38.687 回答
0

尝试使用JavaScriptSerializer类:http: //msdn.microsoft.com/ru-ru/library/system.web.script.serialization.javascriptserializer.aspx

于 2013-08-22T06:25:13.250 回答