简体   繁体   English

你会如何 c# 中的 model 和 json

[英]How would you model a json in c#

I have a JSON like我有一个 JSON 之类的

{
    "myObject":{
        "Difficult": true,
        "Impossible": false
    }
}

and a model like和 model 之类的

public class Blas
{
    public string something { get; set; }
    public int somethinElse { get; set; }
    public Dictionary<string, bool> myObject{ get; set; } //this is how I'm currently modeling the JSON
}

and when I use it I'm doing myObject["Difficult"];当我使用它时,我正在做myObject["Difficult"]; but I need to do something like if(myObject.Difficult)..但我需要做类似if(myObject.Difficult)..

Note to duplicate suggestion: The suggestion is irrelevant because as the title says, my question is regarding to model a JSON in C#, not converting.注意重复建议:该建议无关紧要,因为正如标题所述,我的问题是关于 C# 中的 model 和 JSON,而不是转换。 I can convert, but I need to improve my current modeling in c#.我可以转换,但我需要改进 c# 中的当前建模。

add class "MyObject" like this像这样添加 class "MyObject"

Import进口

using Newtonsoft.Json

Code代码

public class MyObject
{
    [JsonProperty("Difficult")]
    public bool Difficult { get; set; }
    [JsonProperty("Impossible")]
    public bool Impossible { get; set; }
}

public class MyData {
    [JsonProperty("myObject")]
    public MyObject { get; set; }
}

then, define class like this然后,像这样定义 class

MyData obj = JsonConvert.DeserializeObject<MyData>(jsonString);

jsonString would be your json string. jsonString 将是您的 json 字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM