C# 在c中删除Json数组中的Json对象
我对c语言编程和 我有一个JSON字符串:C# 在c中删除Json数组中的Json对象,c#,arrays,json,C#,Arrays,Json,我对c语言编程和 我有一个JSON字符串: { "Type": "Name", "parameters": [ { "A": { "type": "string", "defaultValue": "key" }, "B": { "type": "string", "defaultValue": "key" }, "C": { "type":
{
"Type": "Name",
"parameters": [
{
"A": {
"type": "string",
"defaultValue": "key"
},
"B": {
"type": "string",
"defaultValue": "key"
},
"C": {
"type": "string",
"defaultValue": "key"
},
"D": {
"type": "string",
"defaultValue": "autogenerated"
},
"E": {
"type": "string",
"defaultValue": "autogenerated"
},
"F": {
"type": "dropdown",
"dropDownItems": [
"true",
"false"
],
"defaultValue": "false"
}
}
]
}
我想输出JSON数组参数,但不包括A、B和C。
这个JSON文件总是在变化,但它总是有A、B和C。答案是Thierry Prost
namespace Testedouble
{
class Program
{
static void Main(string[] args)
{
var jsonString = @"{
'Type': 'Name',
'parameters': [
{
'A': {
'type': 'string',
'defaultValue': 'key'
},
'B': {
'type': 'string',
'defaultValue': 'key'
},
'C': {
'type': 'string',
'defaultValue': 'key'
},
'D': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'E': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'F': {
'type': 'dropdown',
'dropDownItems': [
'true',
'false'
],
'defaultValue': 'false'
}
}
]
}";
var values = JsonConvert.DeserializeObject<Foo>(jsonString);
foreach (var key in new string[] { "A", "B", "C" })
{
foreach (var item in values.parameters)
{
item.Remove(key);
}
}
Console.WriteLine(JsonConvert.SerializeObject(values));
}
public class Foo
{
public string Type { get; set; }
public List<Dictionary<string, object>> Parameters { get; set; }
}
}
}
使用
增加
使用Newtonsoft.Json包:
using System;
using Newtonsoft.Json;
using System.IO;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//File with json
string jsontext = File.ReadAllText("json.json");
dynamic json = JsonConvert.DeserializeObject(jsontext);
foreach(var parameter in json.parameters)
{
Console.WriteLine(parameter.D);
Console.WriteLine(parameter.E);
Console.WriteLine(parameter.F);
}
Console.ReadLine();
}
}
}
1使用Newtonsoft.json.Linq将json解析为命名空间下的JObject
2使用JObject.SelectToken检索参数数组中的第一个对象
3使用JObject移除A、B、C。移除
输出:来自调试器
我制作了一个小的控制台应用程序,显示了期望的结果。流程如下: 我们为给定的JSON创建所需的C类:DropdownInfo、ParameterInfo、ParameterBase、Base。我做了几个这样你就可以根据需要更好地扩展它们。 我们对对象进行反序列化,然后按照我们想要的方式对其进行修改。 var itemsToRemove=新字符串[]{A,B,C}; 在这里,我们添加了我们不希望出现在输出中的所有元素。在我们的例子中,我们去掉A,B,C -将对象序列化回JSON。我们使用格式。缩进,所以结果看起来更漂亮,更易读
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace JsonExercise
{
public class JsonExercise
{
public static void Main(string[] args)
{
var sb = new StringBuilder();
var line = string.Empty;
while (!string.IsNullOrWhiteSpace((line = Console.ReadLine())))
{
sb.AppendLine(line);
}
var json = sb.ToString().Trim();
var inputObj = JsonConvert.DeserializeObject<Base>(json);
var resultObj = new
{
Type = inputObj.Type,
Parameters = new List<object>()
};
Console.WriteLine("--------------------------------");
//Here we can give all the Properties, which will be skipped!
var itemsToRemove = new string[] { "A", "B", "C" };
var propertiesToAdd = new Dictionary<string, object>();
foreach (var propertyInfo in typeof(ParameterBase).GetProperties())
{
if (!itemsToRemove.Contains(propertyInfo.Name))
{
var propertyValue = (inputObj.Parameters[0]).GetType().GetProperty(propertyInfo.Name).GetValue(inputObj.Parameters[0]);
propertiesToAdd.Add($"{propertyInfo.Name}", propertyValue);
}
}
var objToAdd = GetDynamicObject(propertiesToAdd);
resultObj.Parameters.Add(objToAdd);
Console.WriteLine("Serializing Object");
Console.WriteLine(JsonConvert.SerializeObject(resultObj, Formatting.Indented));
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
public class Base
{
public string Type { get; set; }
public ParameterBase[] Parameters { get; set; }
}
public class ParameterBase
{
public ParameterInfo A { get; set; }
public ParameterInfo B { get; set; }
public ParameterInfo C { get; set; }
public ParameterInfo D { get; set; }
public ParameterInfo E { get; set; }
public DropdownInfo F { get; set; }
}
public class ParameterInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
}
public class DropdownInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
public string[] DropDownItems { get; set; }
}
}
-输出-
编辑:在@João Paulo Amorim comment之后更改了代码。我测试了代码,它运行良好,可以自由使用。
向圣保罗·阿莫林大声呼喊,回答他。看起来更平滑
注:我关于StackOverFlow的第一个答案\o/我忘了提到这个json文件总是在变化,我不能把它放在c类中。检查这个:我用输出截图添加了我的答案试试看,让我知道:这是一个字典列表!参数应该是列表参数{get;set;}在这个答案中,我只需要将公共字典参数{get;set;}替换为公共列表参数{get;set;}。正确吗?添加了Working fiddle。您没有删除D、E、F,您只是选择了其他选项,如果出现新选项,它将不会显示在您的代码中,您应该删除所需的选项,而不仅仅是选择所有其他选项。感谢您的通知,我编辑了整个代码。经过测试,它工作良好,还添加了新的东西。如果我得到了足够的声誉,你们这边的好答案会让我更满意。谢谢你们,在其他评论中见^^
using System;
using Newtonsoft.Json;
using System.IO;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//File with json
string jsontext = File.ReadAllText("json.json");
dynamic json = JsonConvert.DeserializeObject(jsontext);
foreach(var parameter in json.parameters)
{
Console.WriteLine(parameter.D);
Console.WriteLine(parameter.E);
Console.WriteLine(parameter.F);
}
Console.ReadLine();
}
}
}
string json = "Your json here";
JObject jObject = JObject.Parse(json);
JObject jObj = (JObject)jObject.SelectToken("parameters[0]");
jObj.Property("A").Remove();
jObj.Property("B").Remove();
jObj.Property("C").Remove();
string output = jObject.ToString();
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace JsonExercise
{
public class JsonExercise
{
public static void Main(string[] args)
{
var sb = new StringBuilder();
var line = string.Empty;
while (!string.IsNullOrWhiteSpace((line = Console.ReadLine())))
{
sb.AppendLine(line);
}
var json = sb.ToString().Trim();
var inputObj = JsonConvert.DeserializeObject<Base>(json);
var resultObj = new
{
Type = inputObj.Type,
Parameters = new List<object>()
};
Console.WriteLine("--------------------------------");
//Here we can give all the Properties, which will be skipped!
var itemsToRemove = new string[] { "A", "B", "C" };
var propertiesToAdd = new Dictionary<string, object>();
foreach (var propertyInfo in typeof(ParameterBase).GetProperties())
{
if (!itemsToRemove.Contains(propertyInfo.Name))
{
var propertyValue = (inputObj.Parameters[0]).GetType().GetProperty(propertyInfo.Name).GetValue(inputObj.Parameters[0]);
propertiesToAdd.Add($"{propertyInfo.Name}", propertyValue);
}
}
var objToAdd = GetDynamicObject(propertiesToAdd);
resultObj.Parameters.Add(objToAdd);
Console.WriteLine("Serializing Object");
Console.WriteLine(JsonConvert.SerializeObject(resultObj, Formatting.Indented));
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
public class Base
{
public string Type { get; set; }
public ParameterBase[] Parameters { get; set; }
}
public class ParameterBase
{
public ParameterInfo A { get; set; }
public ParameterInfo B { get; set; }
public ParameterInfo C { get; set; }
public ParameterInfo D { get; set; }
public ParameterInfo E { get; set; }
public DropdownInfo F { get; set; }
}
public class ParameterInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
}
public class DropdownInfo
{
public string Type { get; set; }
public string DefaultValue { get; set; }
public string[] DropDownItems { get; set; }
}
}
{
"Type": "Name",
"parameters": [
{
"A": {
"type": "string",
"defaultValue": "key"
},
"B": {
"type": "string",
"defaultValue": "key"
},
"C": {
"type": "string",
"defaultValue": "key"
},
"D": {
"type": "string",
"defaultValue": "autogenerated"
},
"E": {
"type": "string",
"defaultValue": "autogenerated"
},
"F": {
"type": "dropdown",
"dropDownItems": [
"true",
"false"
],
"defaultValue": "false"
}
}
]
}
{
"Type": "Name",
"Parameters": [
{
"D": {
"Type": "string",
"DefaultValue": "autogenerated"
},
"E": {
"Type": "string",
"DefaultValue": "autogenerated"
},
"F": {
"Type": "dropdown",
"DefaultValue": "false",
"DropDownItems": [
"true",
"false"
]
}
}
]
}