【问题标题】:Map JSon property to variable inside JSon string?将JSon属性映射到JSon字符串中的变量?
【发布时间】:2014-06-17 19:52:41
【问题描述】:

我正在寻找一种使用 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.NET deserialize/serialize JsonProperty JsonObject

【问题讨论】:

    标签: c# json web-services json.net deserialization


    【解决方案1】:

    您可以简单地使用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# 中是保留字,我在它们前面使用了 @

    【讨论】:

    • 我想过这个。不过,我更希望有一个可以反序列化的对象。
    • 我这样说是因为我正在处理的 json 可能长达数十万行(我不想每次想反序列化时都创建一个对象)
    • 刚刚意识到那是我的错(我一直在研究两个类似的反序列化代码并将它们混合起来)我编辑了问题以反映我的实际问题。很抱歉!
    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 2020-02-23
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2020-12-27
    相关资源
    最近更新 更多