将JSon属性映射到JSon字符串中的变量

本文关键字:JSon 变量 字符串 属性 映射 | 更新日期: 2023-09-27 18:08:58

我正在寻找一种方法将多个属性映射到使用newtonsoft的JSon字符串的不同"部分"。

我目前拥有的是以下内容(根本不起作用,但也许你会更好地了解我正在努力完成的内容):

public class example
{
  [JsonProperty("this.is.an.example")]
  public string ex { get; set; }
  [JsonProperty("this.is.another")]
  public string ex2;
}

而相应的JSon字符串的结构可能如下所示:

{
  "this" :
  {
    "is" : {
      "an" : {
        "example" : "this is the first value I want to return"
      }
      "another" : "this is the second value"
    }
  }
}

这样我就可以轻松地反序列化这些JSon字符串,如下所示:

example y = JsonConvert.DeserializeObject<example>(x);
//where x is the JSon string shown above and
//y.ex == "this is the first value I want to return"
//y.ex2 == "this is the second value
//Also note that example is the class name of the resulting object

希望你能看到我在努力完成什么。提前感谢任何帮助,任何输入是感激的!

注意:

经过一番搜索,我发现了一个类似的问题,但没有得到答案。但它可能对JSON有帮助。JsonObject

将JSon属性映射到JSon字符串中的变量

您可以简单地使用dynamic关键字,而不是编写一些复杂的自定义反序列化代码。

string json = @"{""this"":{""is"":{""an"":{""example"":""this is the first value I want to return""}}}}";
dynamic jObj = JObject.Parse(json);
string example = jObj.@this.@is.an.example;

PS:由于thisis是c#中的保留字,我在它们前面使用了@