gpt4 book ai didi

c# - 如何使用 ServiceStack 增量序列化和反序列化 JSON?

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:34 25 4
gpt4 key购买 nike

我的是这样的:

string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";

如何读取字段直到到达“对象”,然后将整个“对象”序列化为 .NET 类型,然后继续解析?

最佳答案

定义你的类型:

public class Object
{
public int t { get; set; }
public string whatever { get; set; }
public string str { get; set; }
}

public class RootObject
{
public int number { get; set; }
public Object object { get; set; }
}

然后反序列化它:

string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
//do what you want

更新

你没说是动态的,这样的解析有很多方案。

检查以下内容:

Using JSON.NET for dynamic JSON parsing

Using C# 4.0 and dynamic to parse JSON

Deserialize JSON into C# dynamic object?

Parse JSON block with dynamic variables

Turning JSON into a ExpandoObject

处理动态类型:使用dynamic,处理XMLJSON等动态数据使用ExpandoObject.

更新 2

Using Anonymous types to deserialize JSON data

更新 3

这对你有用吗:

 string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = SimpleJson.DeserializeObject<IDictionary<string, object>>(json);

var yourObject = deserialized["object"] as IDictionary<string, object>;
if (yourObject != null)
{
var tValue = yourObject.GetValue("t");
var whateverValue = yourObject.GetValue("whatever");
var strValue = yourObject.GetValue("str");
}

public static object GetValue(this IDictionary<string,object> yourObject, string propertyName)
{
return yourObject.FirstOrDefault(p => p.Key == propertyName).Value;
}

最终结果:

enter image description here

或者改成下面的

if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}

enter image description here

更新 4 - 服务堆栈

string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = JsonObject.Parse(json);

var yourObject = deserialized.Get<IDictionary<string, object>>("object");

if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}

结果:

enter image description here

关于c# - 如何使用 ServiceStack 增量序列化和反序列化 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com