c# - 接收 json 并返回来自 json 的两个字段并执行相反操作的方法
问题描述
基本上,我想做一个方法,用 JSON 的两个字段创建并返回一个通用对象(C#)
目的
{"value": 1, "type": "int"}
{"value": "true", "type": "boolean"}
{"value": "dfsfd", "type": "string"}
{"value": "31/03/2020", "type": "datetime"}
解决方案
您的 JSON 格式错误。它应该看起来更像下面。
选项1:
{ "Classes": [
{"value": "sdasd", "type": "int"},
{"value": "sds", "type": "boolean"},
{"value": "sd", "type": "string"},
{"value": "sdds", "type": "datetime"}
]}
这是 JSON 中的对象数组。如果这是换行符分隔的 JSON,老实说,我对此一无所知。
接下来,您必须创建一个类,将这个 JSON 反序列化为。
public class CollectionOfMyClass
{
public List<MyClass> Classes { get; set; }
}
public class MyClass
{
public object Value { get; set; }
public object Type { get; set; }
}
然后使用 Newtonsoft.Json 反序列化
public CollectionOfMyClass GetCollection(string jsonString)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<CollectionOfMyClass>(jsonString);
}
选项 2:这是一种更通用的方法
杰森:
[
{"value": "sdasd", "type": "int"},
{"value": "sds", "type": "boolean"},
{"value": "sd", "type": "string"},
{"value": "sdds", "type": "datetime"}
]
使用 Newtonsoft.JSON 反序列化:
public List<Dictionary<object, object>> GetCollection1(string jsonString)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(jsonString);
}
推荐阅读
- html - 在 ngx-scrollreveal 中,ngsReveal 是隐藏组件,应该在滚动时进行动画处理
- c# - 如何洗牌datagridview?
- django - Django - 将模型 CharField 值设置为来自另一个模型的字段名称
- nested - Powerbuilder 获取嵌套数据窗口的对象
- python - 如何从行中获取 strptime 并与当前时间进行比较?
- javascript - 使用带有多个图像目标的 8th Wall SDK 进行增强
- swift - 将通用对象存储在异构数组中并将对象参数检索为正确的类型
- java - 无法从 hashmap 和 gson 获取正确的 json
- javascript - 无法导入 JavaScript 类
- python - 如何使用 python opencv 和 ffmpeg 同步视频和音频?