JSON.net을 사용하여 JSON 구조를 사전으로 역 직렬화하려고합니다. 트릭은 JSON 문서가 중첩 된 객체의 계층 구조이지만 최상위 속성 + 값 쌍만보고 싶습니다.
예 :
{
"prop1": 142,
"prop2": "Some description",
"object_prop": {
"abc": 2,
"def": {
"foo": "hello",
"bar": 4
}
}
}
위의 예를 기반으로 역 직렬화 된 사전에 "prop1", "prop2"및 "object_prop"의 3 개 항목이 포함되도록하고 싶습니다. "object_prop"는 문자열이어야합니다 (나중에 객체로 역 직렬화 할 것입니다).
참고 : 최상위 키 / 값 쌍과 라이브러리를 사용하는 클라이언트가 나중에 값의 유형을 정의 할 수있는 위치 만 알고있는 재사용 가능한 라이브러리를 만들고 싶기 때문에이 작업을 수행하려고합니다. (즉, 재사용 가능한 라이브러리가 객체 유형에 바인딩되는 것을 원하지 않습니다. 즉 "object_prop").
이런 건 어때?
class Program
{
static void Main(string[] args)
{
string json = @"
{
""prop1"": 142,
""prop2"": ""Some description"",
""object_prop"": {
""abc"": 2,
""def"": {
""foo"": ""hello"",
""bar"": 4
}
},
""prop3"": 3.14
}";
Dictionary<string, string> dict = new Dictionary<string, string>();
JObject jo = JObject.Parse(json);
foreach (JProperty prop in jo.Properties())
{
if (prop.Value.Type == JTokenType.Array ||
prop.Value.Type == JTokenType.Object)
{
// JSON string for complex object
dict.Add(prop.Name, prop.Value.ToString(Formatting.None));
}
else
{
// primitive value converted to string
object value = ((JValue)prop.Value).Value;
dict.Add(prop.Name, value != null ? value.ToString() : null);
}
}
foreach (KeyValuePair<string, string> kvp in dict)
{
Console.WriteLine(kvp.Key + " = " + kvp.Value);
}
}
}
산출:
prop1 = 142
prop2 = Some description
object_prop = {"abc":2,"def":{"foo":"hello","bar":4}}
prop3 = 3.14
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다