gpt4 book ai didi

c# - JavaScriptSerializer 反序列化为嵌套对象

转载 作者:行者123 更新时间:2023-12-03 12:38:54 26 4
gpt4 key购买 nike

我有一个包含三个参数的对象(称为表达式): term1 操作 term2 其中 term1 和 term2 是对象,操作是字符串。处理对象的逻辑可以处理 term1 或 term2 作为字符串或包含嵌入表达式的递归场景。

[DataContract] public class expression
{
[DataMember] public object term1 { get; set; }
[DataMember] public string operation { get; set; }
[DataMember] public object term2 { get; set; }
}

当我尝试反序列化 term1/term2 是简单字符串的对象时,效果很好,即

{ term1: "foo", operation: "=", term2: "bar" }

将使用 C# JavaScriptSerializer 和以下代码正确反序列化:

    public T deserialize_json<T>(string json_string)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return (T)serializer.Deserialize<T>(json_string);
}

但是,当我尝试提交嵌套对象时,即:

{ 
term1:
{
term1: "foo", operation: "=", term2: "bar"
},
operation: "or",
term2:
{
term1: "foo", operation: "equals", term2: "baz"
}
}

JavaScriptSerializer 会将 term1 和 term2 反序列化为 'System.Collections.Generic.Dictionary2[System.String,System.Object]'`

有什么想法吗?

我的方法调用很简单:

expression expr = deserialize<expression>(data);

最佳答案

您需要序列化有关 term1 和 term2 类型的信息。为此,您可以使用 Newtonsoft.Json 库。

试试这个代码:

expression model = new expression() { term1 = new expression() { operation = " + " } };
string content = ModelManager<expression>.SaveToString(model);
/* content =
{
"$type": "Test.expression, Test",
"term1": {
"$type": "Test.expression, Test",
"operation": " + "
}
}
*/
var model2 = ModelManager<expression>.LoadFromString(content);
string content2 = ModelManager<expression>.SaveToString(model2);
// content == content2

public static class ModelManager<T>
{
public static T LoadFromString(string content)
{
using (var sr = new StringReader(content))
using (var jr = new JsonTextReader(sr))
return GetSerializer().Deserialize<T>(jr);
}
public static string SaveToString(T model)
{
StringBuilder sb = new StringBuilder(512);

using (var sw = new StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture))
using (var jtw = new JsonTextWriter(sw))
GetSerializer().Serialize(jtw, model);

return sb.ToString();
}

private static Newtonsoft.Json.JsonSerializer GetSerializer()
{
return new Newtonsoft.Json.JsonSerializer()
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include,
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
Formatting = Formatting.Indented,
MaxDepth = null,
ReferenceLoopHandling = ReferenceLoopHandling.Error,
PreserveReferencesHandling = PreserveReferencesHandling.None
};
}
}

关于c# - JavaScriptSerializer 反序列化为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599306/

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