it-source

리스트의 시리얼화>를 JSON으로 합니다.

criticalcode 2023. 4. 6. 21:45
반응형

리스트의 시리얼화>를 JSON으로 합니다.

JSON은 처음이니까 도와주세요!

를 연재하려고 합니다.List<KeyValuePair<string, string>>JSON으로서

현재:

[{"Key":"MyKey 1","Value":"MyValue 1"},{"Key":"MyKey 2","Value":"MyValue 2"}]

예상:

[{"MyKey 1":"MyValue 1"},{"MyKey 2":"MyValue 2"}]

이것과 이것에서 예를 몇 가지 들었다.

이것은 Key ValuePairJsonConverter : JsonConverter 입니다.

public class KeyValuePairJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<KeyValuePair<object, object>> list = value as List<KeyValuePair<object, object>>;
        writer.WriteStartArray();
        foreach (var item in list)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(item.Key.ToString());
            writer.WriteValue(item.Value.ToString());
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<KeyValuePair<object, object>>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jsonObject = JObject.Load(reader);
        var target = Create(objectType, jsonObject);
        serializer.Populate(jsonObject.CreateReader(), target);
        return target;
    }

    private object Create(Type objectType, JObject jsonObject)
    {
        if (FieldExists("Key", jsonObject))
        {
            return jsonObject["Key"].ToString();
        }

        if (FieldExists("Value", jsonObject))
        {
            return jsonObject["Value"].ToString();
        }
        return null;
    }

    private bool FieldExists(string fieldName, JObject jsonObject)
    {
        return jsonObject[fieldName] != null;
    }
}

이렇게 WebService 방식으로 호출합니다.

List<KeyValuePair<string, string>> valuesList = new List<KeyValuePair<string, string>>();
Dictionary<string, string> valuesDict = SomeDictionaryMethod();

foreach(KeyValuePair<string, string> keyValue in valuesDict)
{
    valuesList.Add(keyValue);
}

JsonSerializerSettings jsonSettings = new JsonSerializerSettings { Converters = new [] {new KeyValuePairJsonConverter()} };
string valuesJson = JsonConvert.SerializeObject(valuesList, jsonSettings);

Newtonsoft 및 사전을 사용할 수 있습니다.

    var dict = new Dictionary<int, string>();
    dict.Add(1, "one");
    dict.Add(2, "two");

    var output = Newtonsoft.Json.JsonConvert.SerializeObject(dict);

출력은 다음과 같습니다.

{"1":"one","2":"two"}

편집

정보를 주신 @Sergey Berezovskiy님 감사합니다.

현재 Newtonsoft를 사용 중이므로 변경만 하면 됩니다.List<KeyValuePair<object, object>>로.Dictionary<object,object>패키지의 serialize 및 deserialize 방식을 사용합니다.

그래서 비슷한 문제를 해결하기 위해 네이티브 c# 이외에는 사용하고 싶지 않았습니다.참고로 .net 4, jquery 3.2.1 및 backbone 1.2.0을 사용하고 있습니다.

제 고민은...List<KeyValuePair<...>>는 컨트롤러에서 백본모델로 처리됩니다만, 그 모델을 보존했을 때, 컨트롤러는 리스트를 바인드 할 수 없었습니다.

public class SomeModel {
    List<KeyValuePair<int, String>> SomeList { get; set; }
}

[HttpGet]
SomeControllerMethod() {
    SomeModel someModel = new SomeModel();
    someModel.SomeList = GetListSortedAlphabetically();
    return this.Json(someModel, JsonBehavior.AllowGet);
}

네트워크 캡처:

"SomeList":[{"Key":13,"Value":"aaab"},{"Key":248,"Value":"aaac"}]

backing model.js에서 SomeList를 올바르게 설정해도 변경 없이 모델을 저장하려고 하면 바인딩된 SomeModel 객체의 길이는 요청 본문의 파라미터와 동일하지만 모든 키와 값은 null입니다.

[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
    SomeModel.SomeList; // Count = 2, all keys and values null.
}

KeyValuePair는 이런 식으로 인스턴스화할 수 있는 것이 아니라 구조라는 것밖에 찾을 수 없었습니다.저는 다음과 같은 일을 하게 되었습니다.

  • 키, 값 필드가 포함된 모델 래퍼를 추가합니다.

    public class KeyValuePairWrapper {
        public int Key { get; set; }
        public String Value { get; set; }
    
        //default constructor will be required for binding, the Web.MVC binder will invoke this and set the Key and Value accordingly.
        public KeyValuePairWrapper() { }
    
        //a convenience method which allows you to set the values while sorting
        public KeyValuePairWrapper(int key, String value)
        {
            Key = key;
            Value = value;
        }
    }
    
  • 사용자 지정 래퍼 개체를 수락하도록 바인딩 클래스 모델을 설정합니다.

    public class SomeModel
    {
        public List<KeyValuePairWrapper> KeyValuePairList{ get; set }; 
    }
    
  • 컨트롤러에서 json 데이터 가져오기

    [HttpGet]
    SomeControllerMethod() {
        SomeModel someModel = new SomeModel();
        someModel.KeyValuePairList = GetListSortedAlphabetically();
        return this.Json(someModel, JsonBehavior.AllowGet);
    }
    
  • 나중에 작업을 수행합니다.model.save(null, ...)가 호출됩니다.

    [HttpPut]
    SomeControllerMethod([FromBody] SomeModel){
        SomeModel.KeyValuePairList ; // Count = 2, all keys and values are correct.
    }
    

언급URL : https://stackoverflow.com/questions/41503024/serialize-listkeyvaluepairstring-string-as-json

반응형