将json字符串反序列化为使用newtonsoft的c#对象
问题描述:
我一直在使用该项目,我必须使外部RESTful服务调用来获取某些数据。将json字符串反序列化为使用newtonsoft的c#对象
我在这里面临的问题是,我从服务中得到的回应在不同情况下是不同的。例如。
在一个场景中,我得到如下回应
{
"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":[]
}
这里的问题是,我有以下的模型,而且我通过牛顿软删除来反序列化它。
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; }
}
对于第一个响应,它将进行绝对化。但对于第二个响应,响应不会被反序列化,因为对于Customer
和ApplicationAddrees
对象,响应包含[]
。反序列化时,它被视为一个数组,但事实上并非如此。
注意:下面的代码我用于反序列化。 响应响应= JsonConvert.DeserializeObject(result);
在序列化之前我们可以做任何配置吗?牛顿软件是否有利于该功能?
谢谢。
答
不能指示反序列化处理“[]”作为不同的东西,因为它代表一个数组(你确定你永远不会得到客户和地址的阵列?)
,所以你可以deserialize to an anonymous type和然后将其映射到您的结构。
答
如果你确信不会有数组这个特性,比你可以考虑使用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();
}
}
然后把额外attribure到你的模型:
[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; }
}
}
能否请您分享您的通话反序列化? –
对于不同的场景,使用不同的类进行反序列化。第一个示例使用您拥有的类,第二个示例使用列表,List 属性的类。您可以为共享属性使用基类。它是您为不同场景调用的单个终端吗? –
@TimBourguignon,我用反序列化代码更新了问题。 – PaRsH