JSON模式:
{
"title": "Amenities",
"additionalProperties": false,
"properties": {
"Footer": {
"type": "string",
"editType": "textarea"
},
"RowType": {
"type": "integer",
"editType": null
},
"answers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"answer": {
"type": "integer",
"editType": null
},
"FooterInner": {
"type": "string",
"editType": "textarea"
}
}
}
}
},
"type": "object"
}
JSON对象:
{
"Footer": "",
"RowType": 0,
"answers": [
{
"answer": 1,
"FooterInner": "innerfooter"
},
{
"answer": 2,
"FooterInner": "innerfooter2"
}
]
}
我需要在JSON模式中使用"type=integer"
查找属性,并将这些属性从JSON对象中删除。
预期的JSON对象为:
{
"Footer": "",
"answers": [
{
"FooterInner": "innerfooter"
},
{
"FooterInner": "innerfooter2"
}
]
}
JSON模式和JSON对象可能有所不同,因此我需要验证并从任何类型的JSON对象中删除"type=integer"
属性。
我已经搜索过,找不到有用的东西,主要问题是JSON中可能有多个嵌套元素。
可能我需要编写递归迭代函数,是否有任何现有解决方案?
答案 0 :(得分:2)
这是解决方案:
我不是在模式中搜索"type=integer"
属性,而是在JSON对象中完成的。
但是,首先,我针对JSON object
验证了JSON schema
,以确保JSON object
中没有任何其他属性。
1.Step -根据JSON模式验证JSON对象:
JsonValue loadedSchema = JsonValue.Parse(jsonSchema);
var schema = JsonSchemaFactory.FromJson(loadedSchema);
JsonValue loadedObject = JsonValue.Parse(json);
var schemaValidationResult = schema.Validate(loadedObject);
如果1.Step正确,则执行2.Step
2.Step -从JSON对象中删除Integer,Boolean和Float类型的属性:
static void Main(string[] args)
{
var json =
@"{
""Footer"": ""footer"",
""RowType"": 4,
""answers"":
[
{
""answer"": 1,
""FooterInner"": ""innerfooter""
},
{
""answer"": 2,
""FooterInner"": ""innerfooter2""
}
]
}";
JToken nodeList = JToken.Parse(json);
List<JTokenType> typesToRemove = new List<JTokenType>(){JTokenType.Boolean, JTokenType.Float, JTokenType.Integer};
removeFields(nodeList, typesToRemove);
Console.WriteLine(nodeList.ToString());
Console.ReadKey();
}
private static void removeFields(JToken token, List<JTokenType> typesToRemove)
{
JContainer container = token as JContainer;
if (container == null) return;
List<JToken> removeList = new List<JToken>();
foreach (JToken el in container.Children())
{
JProperty p = el as JProperty;
if (p != null && typesToRemove.Contains(p.Value.Type))
{
removeList.Add(el);
}
removeFields(el, typesToRemove);
}
foreach (JToken el in removeList)
{
el.Remove();
}
}
答案 1 :(得分:0)
我认为您在这里有2个选择: