[英]Deserialize json string to c# object using newtonsoft
我一直在使用該項目,我必須進行外部RESTful服務調用以獲取一些數據。
我面臨的問題是,我從服務中獲得的響應在不同的場景中是不同的。 例如。
在一種情況下,我得到低於響應
{
"id":3000056,
"posted_date":"2016-04-15T07:16:47+00:00",
"current_status":"initialized",
"customer":{
"name" : "George",
"lastName" : "Mike"
},
"application_address":{
"addressLine1" : "Lin1",
"addressLine2" : "Lin2",
}
}
在另一種情況下,我得到低於響應
{
"id":3000057,
"posted_date":"2016-04-15T07:16:47+00:00",
"current_status":"initialized",
"customer":[],
"application_address":[]
}
這里的問題是,我有以下模型,我通過newtonsoft deserailization進行反序列化。
public class Response
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("posted_date")]
public DateTime PostedDate { get; set; }
[JsonProperty("current_status")]
public string CurrentStatus { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("application_address")]
public ApplicationAddress ApplicationAddress { get; set; }
}
public Class Customer
{
public string name { get; set; }
public string lastName { get; set; }
}
public classs ApplicationAddress
{
public string addreesLine1{ get; set; }
public string addreesLine1{ get; set; }
}
對於第一個響應,它將desrialize。 但是對於第二個響應,響應沒有被反序列化,因為響應包含Customer
和ApplicationAddrees
對象的[]
。 在反序列化時,它被視為一個數組,但實際上並非如此。
注意:下面我用於反序列化的代碼。 響應響應= JsonConvert.DeserializeObject(result);
在序列化之前我們可以做任何配置嗎? newtonsoft是否有助於該功能?
謝謝 。
如果您確定此屬性中沒有數組,那么您可以考慮使用JsonConverter,如下所示:
public class FakeArrayToNullConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return null;
}
return token.ToObject<T>();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后對您的模型進行額外的歸因:
[JsonProperty("customer")]
[JsonConverter(typeof(FakeArrayToNullConverter<Customer>))]
public Customer Customers { get; set; }
[JsonProperty("application_address")]
[JsonConverter(typeof(FakeArrayToNullConverter<ApplicationAddress>))]
public ApplicationAddress ApplicationAddressList { get; set; }
當你在這個屬性的JSON字符串中它將是一個數組[]
,你只需用null
對象反序列化它。
您不能指示反序列化處理“[]”作為一個不同的東西,因為它代表一個數組(你確定你永遠不會得到這些數組中的客戶和地址??)
因此,您可以反序列化為匿名類型 ,然后將其映射到您的結構。
這只是一個猜測,但你可以檢查這是否有效:
public class ApplicationAddress
{
private readonly string[] _array = new string[2];
public string this[int index]
{
get { return _array[index]; }
set { _array[index] = value; }
}
public string addreesLine1
{
get { return this[0]; }
set { this[0] = value; }
}
public string addreesLine2
{
get { return this[1]; }
set { this[1] = value; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.