是否可以将json文档的特定部分“提升”为数组?
例如,输入内容如下:
{
"identifier": {"a":"awesome", "b":"back", "c":"cat"}
}
假设我想推广c
,在伪代码中,我们将执行以下操作:
var payload = "{\"identifier\": {\"a\":\"awesome\", \"b\":\"back\", \"c\":\"cat\"}}";
var payloadWithPromotedC = Promoter.ToArray(payload, "identifier.c");
结果将类似于:
{
"identifier": {"a":"awesome", "b":"back", "c":["cat"]}
}
我们如何声明地将json文档中的某个节点提升为数组?
答案 0 :(得分:1)
我不确定“声明式”是什么意思,但是按照您的示例,您可以使用Json.Net做这样的事情:
public class Promoter
{
public static string ToArray(string json, string propertyPath)
{
JToken root = JToken.Parse(json);
JToken tokenToPromote = root.SelectToken(propertyPath);
if (tokenToPromote == null)
{
throw new JsonException(propertyPath + " was not found");
}
if (tokenToPromote.Type == JTokenType.Array)
{
return json; // value is already an array so return the original JSON
}
tokenToPromote.Replace(new JArray(tokenToPromote));
return root.ToString(Formatting.None);
}
}
正在运行的演示:https://dotnetfiddle.net/bOUOWD