code

Json.net 을 사용하여 JSON 개체를 동적 개체로 역직렬화

starcafe 2023. 5. 28. 20:57
반응형

Json.net 을 사용하여 JSON 개체를 동적 개체로 역직렬화

json.net 을 사용하여 json 역직렬화에서 동적 객체를 반환할 수 있습니까?저는 다음과 같은 일을 하고 싶습니다.

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

여기 문서: LINQ와 JSON의 JSON.NET

JObject도 참조하십시오.구문 분석 및 JARray.구문 분석

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입니다.

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

이것은 완벽하게 잘 작동합니다.디버거에서 유형을 검사하면 값이 실제로 동적이라는 것을 알 수 있습니다.기본 유형은 다음과 같습니다.JObject유형을 제어하려는 경우(예: 지정)ExpandoObject그럼 그렇게 하세요.

여기에 이미지 설명 입력

동적으로 역직렬화하면 JO 개체가 반환됩니다.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);

예, Json Convert를 사용하여 수행할 수 있습니다.개체를 역직렬화합니다.이를 위해 간단한 작업을 수행합니다.

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.IEnumberable

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 내부에 클래스 A 및 클래스 B 객체가 있다고 가정합니다.모두 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

반응형