2013-08-22 119 views
-1

我有一個API調用,它看起來像的結果:自定義JSON,轉換爲對象

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

感謝, 安德魯

+0

什麼是 「自定義」 JSON是什麼意思? –

+1

請看看這個StackOverflow的答案: [http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object][1] [1]:http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object – RRR

+1

使用[json.net](http://james.newtonking的.com /項目/ JSON-net.aspx) –

回答

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;