首页 > 解决方案 > 接收 json 并返回来自 json 的两个字段并执行相反操作的方法

问题描述

基本上,我想做一个方法,用 JSON 的两个字段创建并返回一个通用对象(C#)

目的

{"value": 1, "type": "int"}
{"value": "true", "type": "boolean"}
{"value": "dfsfd", "type": "string"}
{"value": "31/03/2020", "type": "datetime"}

标签: c#.netjsondictionaryjson.net

解决方案


您的 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);
    }

推荐阅读