我想在反序列化一些JSON时使用变量。例如,如果我有JSON字符串(我知道这不是真正有效的JSON):
{
"foo": bar
}
我希望有机会解析符号bar
因此,在反序列化时,我希望以以下内容的反序列化结束:
{
"foo": { "baz": "foobar" }
}
这是可能的使用JSON .NET吗?现在我得到:
Additional information: Unexpected character encountered while parsing value: bar. Path 'foo', line 1, position 9.
您可以创建一个辅助方法来完成此操作。helper方法可以首先将所有内容反序列化到JToken
层次结构,然后使用您提供的替换函数递归地搜索并替换变量。更换后,它可以使用JToken.ToObject()
水合物它到你的目标类(es)。该计划中唯一的问题是原始JSON必须是有效的。因此,我建议为变量使用特殊格式的字符串值,这样就不会有机会与普通字符串值混淆。也许像这样:
{
"foo": "$(bar)"
}
下面是帮助器的代码:
public static class JsonHelper
{
public static T DeserializeAndReplace<T>(string json, Func<string, object> replaceFunc)
{
return ReplaceVariables(JToken.Parse(json), replaceFunc).ToObject<T>();
}
public static JToken ReplaceVariables(JToken token, Func<string, object> replaceFunc)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty prop in token.Children<JProperty>())
{
copy.Add(prop.Name, ReplaceVariables(prop.Value, replaceFunc));
}
return copy;
}
if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
copy.Add(ReplaceVariables(item, replaceFunc));
}
return copy;
}
if (token.Type == JTokenType.String)
{
string s = (string)token;
if (s.StartsWith("$(") && s.EndsWith(")"))
{
object value = replaceFunc(s.Substring(2, s.Length - 3));
return (value != null ? JToken.FromObject(value) : JValue.CreateNull());
}
}
return token;
}
}
下面是演示帮助器的示例:
class Program
{
static void Main(string[] args)
{
string json = @"
[
{
""name"" : ""normal"",
""bar"" : { ""baz"" : ""quux"" }
},
{
""name"" : ""$(cool)"",
""bar"" : ""$(bar)""
},
]";
var list = JsonHelper.DeserializeAndReplace<List<Foo>>(json, ReplaceVariable);
foreach (Foo foo in list)
{
Console.WriteLine("name: " + foo.Name);
Console.WriteLine("bar.baz: " + foo.Bar.Baz);
Console.WriteLine();
}
}
private static object ReplaceVariable(string variable)
{
if (variable == "bar") return new Bar { Baz = "foobar" };
if (variable == "cool") return "whip";
return null;
}
}
class Foo
{
public string Name { get; set; }
public Bar Bar { get; set; }
}
class Bar
{
public string Baz { get; set; }
}
输出:name: normal
bar.baz: quux
name: whip
bar.baz: foobar
小提琴:https://dotnetfiddle.net/5T9lmd