Programing

Json.net을 사용하여 json 객체를 동적 객체로 직렬화 해제

lottogame 2020. 2. 21. 22:02
반응형

Json.net을 사용하여 json 객체를 동적 객체로 직렬화 해제


json.net을 사용하여 json deserialization에서 동적 객체를 반환 할 수 있습니까? 나는 이런 식으로하고 싶다 :

dynamic jsonResponse = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);

최신 json.net 버전은 다음을 허용합니다.

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

산출:

 1000
 string
 6

여기에 문서화 : Json.NET을 사용하여 LINQ to JSON


Json.NET 4.0 릴리스 1부터 다음과 같은 기본 동적 지원이 있습니다.

[Test]
public void DynamicDeserialization()
{
    dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
    jsonResponse.Works = true;
    Console.WriteLine(jsonResponse.message); // Hi
    Console.WriteLine(jsonResponse.Works); // True
    Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
    Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
    Assert.That(jsonResponse, Is.TypeOf<JObject>());
}

물론 현재 버전을 얻는 가장 좋은 방법은 NuGet을 이용하는 것입니다.

의견을 해결하기 위해 업데이트 됨 (2014 년 11 월 12 일) :

이것은 완벽하게 작동합니다. 디버거에서 유형을 검사하면 값이 실제로 dynamic인지 알 수 있습니다. 기본 유형 A는 JObject. 유형을 제어하려면 (예 : 지정 ExpandoObject) 그렇게하십시오.

여기에 이미지 설명을 입력하십시오


동적으로 역 직렬화하면 JObject가 다시 나타납니다. ExpandoObject를 사용하여 원하는 것을 얻을 수 있습니다.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

나는 이것이 오래된 게시물이라는 것을 알고 있지만 JsonConvert는 실제로 다른 방법을 가지고 있으므로

var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);

예, JsonConvert.DeserializeObject를 사용하여 수행 할 수 있습니다. 그렇게하려면 간단하게 수행하십시오.

dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);

참고 : 2010 년 에이 질문에 대답했을 때 어떤 종류의 직렬화없이 직렬화를 해제 할 수있는 방법이 없었으므로 실제 클래스를 정의하지 않고도 직렬화를 해제하고 익명화 클래스를 사용하여 직렬화 해제를 수행 할 수있었습니다.


역 직렬화하려면 일종의 유형이 필요합니다. 당신은 라인을 따라 뭔가를 할 수 있습니다 :

var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());

내 대답은 JSON serializer의 .NET 4.0 빌드 솔루션을 기반으로합니다. 익명 유형으로 직렬화 해제 링크는 다음과 같습니다.

http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx


JObject가 아닌 이전 버전으로 JSON.NET을 사용하는 경우.

이것은 JSON에서 동적 객체를 만드는 또 다른 간단한 방법입니다. https://github.com/chsword/jdynamic

NuGet 설치

PM> Install-Package JDynamic

문자열 인덱스를 사용하여 다음과 같은 멤버에 액세스하는 것을 지원하십시오.

dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);

테스트 사례

이 유틸리티는 다음과 같이 사용할 수 있습니다.

직접 가치를 얻으십시오

dynamic json = new JDynamic("1");

//json.Value

2. json 객체에서 멤버 가져 오기

dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"

dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m

dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1

3.IEnumerable

dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements

dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use  json.a[0]/ json.a[2] to get the elements

dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the  json[0].b/json[1].c to get the num.

다른

dynamic json = new JDynamic("{a:{a:1} }");

//json.a.a is 1.

네 가능합니다. 나는 그 일을 계속하고 있습니다.

dynamic Obj = JsonConvert.DeserializeObject(<your json string>);

비 네이티브 유형에는 조금 까다 롭습니다. Obj 내부에 ClassA 및 ClassB 객체가 있다고 가정하십시오. 그것들은 모두 JObject로 변환됩니다. 당신이해야 할 일은 :

ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

참고 URL : https://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net



반응형