在 C# 中将 Json 属性(Nested Json) 反序列化为字符串

Deserialize the Json property(Nested Json) as string in C#

我需要将 json 反序列化为另一个 Json 中可用的字符串。我有如下 Json 字符串,

string testJson =
   "{
        "AssemblyName":"AssemplyName",
        "ClassName":"AssemplyName.ClassName",
        "Options":"{ "property1":"value1","property2":10}"
   }";

要反序列化,我有如下 class,

public class CType
{
    public string AssemblyName { get; set; }
    public string ClassName { get; set; }
    public string Options { get; set; }
}

所以,我反序列化如下,

CType cType = JsonConvert.DeserializeObject<CType>(testJson);

现在,我希望得到如下结果,

AssemblyName = "AssemplyName"
ClassName = "AssemplyName.ClassName"
Options = "{ "property1":"value1","property2":10}"

如果有人能提供帮助,我们将不胜感激

您可以这样声明 class。

public class Options
{
    public string property1 { get; set; }
    public string value1 { get; set; }
    public int property2 { get; set; }
}

public class Example
{
    public string AssemblyName { get; set; }
    public string ClassName { get; set; }
    public Options Options { get; set; }
}

然后你可以像这样反序列化和序列化字符串。

string str = "json string";
Example cType = JsonConvert.DeserializeObject<Example>(str);
string json = JsonConvert.SerializeObject(cType.Options);

有效Json:

{
    "AssemblyName": "AssemplyName",
    "ClassName": "AssemplyName.ClassName",
    "Options": {
        "property1 ": "",
        "value1": "",
        "property2": 10
    }
}

对于动态嵌套 json,您可以将 Options 声明为字典。上面的代码可以工作。

public Dictionary<string, string> Options { get; set; }

要阅读给定 json 的选项形式,您需要使用 TrimDeserializeObject

删除附加引号
var cType = JsonConvert.DeserializeObject<CType>(testJson);
var options = JsonConvert.DeserializeObject<Dictionary<string, string>>(cType.Options.Trim('"'));

假设您希望将选项反序列化为字符串而不是字典 - 您需要更改 json 文件并像下面这样转义引号

{
"AssemblyName": "AssemplyName",
"ClassName": "AssemplyName.ClassName",
"Options": "
\"property1\":\"value1\",
\"property2\": 10   
"
}

完成现有代码

 class Program
{
    static void Main(string[] args)
    {
        string testJson = File.ReadAllText(@"D:\test.json");

        CType cType = JsonConvert.DeserializeObject<CType>(testJson);

    }
}
public class CType
{
    public string AssemblyName { get; set; }
    public string ClassName { get; set; }
    public string Options { get; set; }
}

但是如果你想把它变成另一个像字典一样的对象 - json 需要稍微改变如下

{
"AssemblyName": "AssemplyName",
"ClassName": "AssemplyName.ClassName",
"Options": {
"property1":"value1",
"property2": 10
}
}

代码需要将 属性 更改为字典

 class Program
{
    static void Main(string[] args)
    {
        string testJson = File.ReadAllText(@"D:\test.json");

        CType cType = JsonConvert.DeserializeObject<CType>(testJson);

    }
}
public class CType
{
    public string AssemblyName { get; set; }
    public string ClassName { get; set; }
    public Dictionary<string,string> Options { get; set; }
}