developer tip

Json.net을 사용하여 JSON 객체 배열 역 직렬화

optionbox 2020. 8. 5. 08:08
반응형

Json.net을 사용하여 JSON 객체 배열 역 직렬화


반환 된 json에 다음 예제 구조를 사용하는 API를 사용하려고합니다.

[
   {
      "customer":{
         "first_name":"Test",
         "last_name":"Account",
         "email":"test1@example.com",
         "organization":"",
         "reference":null,
         "id":3545134,
         "created_at":"2013-08-06T15:51:15-04:00",
         "updated_at":"2013-08-06T15:51:15-04:00",
         "address":"",
         "address_2":"",
         "city":"",
         "state":"",
         "zip":"",
         "country":"",
         "phone":""
      }
   },
   {
      "customer":{
         "first_name":"Test",
         "last_name":"Account2",
         "email":"test2@example.com",
         "organization":"",
         "reference":null,
         "id":3570462,
         "created_at":"2013-08-12T11:54:58-04:00",
         "updated_at":"2013-08-12T11:54:58-04:00",
         "address":"",
         "address_2":"",
         "city":"",
         "state":"",
         "zip":"",
         "country":"",
         "phone":""
      }
   }
]

JSON.net은 다음 구조와 같이 잘 작동합니다.

{
    "customer": {
        ["field1" : "value", etc...],
        ["field1" : "value", etc...],
    }
}

그러나 제공된 구조로 행복을 얻는 방법을 알 수는 없습니다.

기본 JsonConvert.DeserializeObject (content)를 사용하면 올바른 수의 고객이 생성되지만 모든 데이터가 널입니다.

CustomerList (아래)를 수행하면 "현재 JSON 배열을 직렬화 해제 할 수 없습니다"예외가 발생합니다.

public class CustomerList
{
    public List<Customer> customer { get; set; }
}

생각?


Json을 직렬화 해제하기 위해 새 모델을 만들 수 있습니다 CustomerJson.

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

그리고 당신은 json을 쉽게 deserialize 할 수 있습니다 :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

그것이 도움이되기를 바랍니다!

설명서 : JSON 직렬화 및 역 직렬화


모델을 작성하지 않으려는 경우 다음 코드를 사용하십시오.

var result = JsonConvert.DeserializeObject<
  List<Dictionary<string, 
    Dictionary<string, string>>>>(content);

Using the accepted answer you have to access each record by using Customers[i].customer, and you need an extra CustomerJson class, which is a little annoying. If you don't want to do that, you can use the following:

public class CustomerList
{
    [JsonConverter(typeof(MyListConverter))]
    public List<Customer> customer { get; set; }
}

Note that I'm using a List<>, not an Array. Now create the following class:

class MyListConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Values())
        {
            var childToken = child.Children().First();
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(childToken.CreateReader(), newObject);
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

Slight modification to what was stated above. My Json format, which validates was

{
    mycollection:{[
           {   
               property0:value,
               property1:value,
             },
             {   
               property0:value,
               property1:value,
             }
           ]

         }
       }

Using AlexDev's response, I did this Looping each child, creating reader from it

 public partial class myModel
{
    public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}

 public class myModelList {
    [JsonConverter(typeof(myModelConverter))]
    public List<myModel> model { get; set; }

}

class myModelConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Children())  //mod here
        {
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(child.CreateReader(), newObject); //mod here
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

}

참고URL : https://stackoverflow.com/questions/18192357/deserializing-json-object-array-with-json-net

반응형

'developer tip' 카테고리의 다른 글

Java-JPA-@Version 주석  (0) 2020.08.05
ADO.NET DataRow-열 존재 여부 확인  (0) 2020.08.05
JPA가있는 Kotlin : 기본 생성자 지옥  (0) 2020.08.04
PHP : 예외와 오류?  (0) 2020.08.04
프레임 워크 비 호환성 로깅  (0) 2020.08.04