自定义JSON,转换为对象

时间:2013-08-22 06:18:40

标签: c# json

我有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解析是否需要知道格式?

谢谢, 安德鲁

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)