简体   繁体   English

使用newtonsoft将json字符串反序列化为c#对象

[英]Deserialize json string to c# object using newtonsoft

I have been working with the project, where i have to make external RESTful service call to get some data. 我一直在使用该项目,我必须进行外部RESTful服务调用以获取一些数据。

The problem i'm facing here is, the response i'm getting from the service is different on different scenario. 我面临的问题是,我从服务中获得的响应在不同的场景中是不同的。 For example. 例如。

On one scenario, i'm getting below response 在一种情况下,我得到低于响应

{  
   "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",
   }

}

In the other scenario, im getting below response 在另一种情况下,我得到低于响应

 {  
   "id":3000057,
   "posted_date":"2016-04-15T07:16:47+00:00",
   "current_status":"initialized",
   "customer":[],
   "application_address":[]

}

The problem here is, i have below model, and i'm deserializing it by newtonsoft deserailization. 这里的问题是,我有以下模型,我通过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; }
}

For the first response, it will desrialize. 对于第一个响应,它将desrialize。 But for the second response, the response is not getting deserialized as the response contains [] for Customer and ApplicationAddrees object. 但是对于第二个响应,响应没有被反序列化,因为响应包含CustomerApplicationAddrees对象的[] While deserializing, it is treating as a array, but actually it is not. 在反序列化时,它被视为一个数组,但实际上并非如此。

Note : Below code i'm using for Deserializing. 注意:下面我用于反序列化的代码。 Response response = JsonConvert.DeserializeObject(result); 响应响应= JsonConvert.DeserializeObject(result);

Is there any configuration we can do before serializing? 在序列化之前我们可以做任何配置吗? Is newtonsoft facilitate that feature? newtonsoft是否有助于该功能?

Thanks . 谢谢 。

If you are sure that there will be no arrays in this properties, than you can consider using JsonConverter like this: 如果您确定此属性中没有数组,那么您可以考虑使用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();
    }
}

And then put additional attribure to your model: 然后对您的模型进行额外的归因:

    [JsonProperty("customer")]
    [JsonConverter(typeof(FakeArrayToNullConverter<Customer>))]
    public Customer Customers { get; set; }

    [JsonProperty("application_address")]
    [JsonConverter(typeof(FakeArrayToNullConverter<ApplicationAddress>))]
    public ApplicationAddress ApplicationAddressList { get; set; }

And when in your JSON string for this properties it will be an array [] , you will simply deserialize it with null object. 当你在这个属性的JSON字符串中它将是一个数组[] ,你只需用null对象反序列化它。

You can't instruct deserialize to handle "[]" as something different as it represents an array (are you sure you never will get customers and addresses in those arrays??) 您不能指示反序列化处理“[]”作为一个不同的东西,因为它代表一个数组(你确定你永远不会得到这些数组中的客户和地址??)

So you could deserialize to an anonymous type and then map it to your structure. 因此,您可以反序列化为匿名类型 ,然后将其映射到您的结构。

This is just a guess but can you check if this works: 这只是一个猜测,但你可以检查这是否有效:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM