programing

JSON 문자열을 사전으로 역직렬화

easyjava 2023. 3. 15. 20:01
반응형

JSON 문자열을 사전으로 역직렬화

다음과 같은 문자열이 있습니다.

[{ "processLevel" : "1" , "segments" : [{ "min" : "0", "max" : "600" }] }]

개체를 역직렬화하는 중입니다.

object json = jsonSerializer.DeserializeObject(jsonString);

오브젝트는 다음과 같습니다.

object[0] = Key: "processLevel", Value: "1"
object[1] = Key: "segments", Value: ...

그리고 사전을 만드는 중:

Dictionary<string, object> dic = json as Dictionary<string, object>;

그렇지만dic얻다null.

문제가 될 수 있는 것은 무엇입니까?

당신이 왜 null을 얻는지에 대해서는 mridula의 답변을 참고하세요.그러나 json 문자열을 직접 사전으로 변환하고 싶다면 다음 코드 스니펫을 사용해 보십시오.

    Dictionary<string, object> values = 
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

저는 이 방법을 좋아합니다.

using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, object>>();

이제 를 사용하여 원하는 모든 항목에 액세스할 수 있습니다.dictObj사전으로서를 사용할 수도 있습니다.Dictionary<string, string>값을 문자열로 가져오려면 이 옵션을 선택합니다.

의 MSDN 매뉴얼as키워드는 스테이트먼트가expression as type스테이트먼트와 동등합니다.expression is type ? (type)expression : (type)null뛰어가면json.GetType()그것은 돌아올 것이다System.Object[]가 아니라System.Collections.Generic.Dictionary.

이와 같이 json 오브젝트를 역직렬화하려는 오브젝트 유형이 복잡한 경우 Json과 같은 API를 사용합니다.NET. 독자적인 디시리얼라이저를 다음과 같이 쓸 수 있습니다.

class DictionaryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        Throw(new NotImplementedException());            
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Your code to deserialize the json into a dictionary object.

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Throw(new NotImplementedException());   
    }
}

그런 다음 이 시리얼라이저를 사용하여 json을 사전 개체로 읽을 수 있습니다.여기 예가 있습니다.

나도 같은 문제가 있어서 해결책을 찾았다.

  • 매우 심플하다
  • 버그 없음
  • 운용 가능한 제품으로 테스트 완료

순서 1) 속성이 2개인 범용 클래스를 만듭니다.

     public class CustomDictionary<T1,T2> where T1:class where T2:class
      {
          public T1 Key { get; set; }
          public T2 Value { get; set; }
      }

스텝 2) 새 클래스를 만들고 퍼스트 클래스에서 상속

  public class SectionDictionary: CustomDictionary<FirstPageSectionModel, List<FirstPageContent>> 
    { 

    }

순서 3) 사전 및 목록 바꾸기

public Dictionary<FirstPageSectionModel, List<FirstPageContent>> Sections { get; set; }

그리고.

 public List<SectionDictionary> Sections { get; set; }

순서 4) 간단하게 시리얼화 또는 디시리얼화

 {
     firstPageFinal.Sections.Add(new SectionDictionary { Key= section,Value= contents });
     var str = JsonConvert.SerializeObject(firstPageFinal);
     var obj = JsonConvert.DeserializeObject<FirstPageByPlatformFinalV2>(str);
 }

정말 감사해요.

문제는 객체가 유형이 아니라는 것입니다.Dictionary<string,object>혹은 호환성이 있는 타입이기 때문에 직접 캐스팅을 할 수 없습니다.커스텀 오브젝트를 생성하여 역직렬화를 사용합니다.

public class DeserializedObject{
    public string processLevel{get;set;}
    public object segments{get;set}
}

IEnumerable<DeserializedObject> object=jsonSerializer.Deserialize<IEnumerable<DeserializedObject>>(json);

언급URL : https://stackoverflow.com/questions/20727787/deserialize-json-string-to-dictionarystring-object

반응형