【问题标题】:Easy way via some attribute to tell JSON deserializer to just stringify json?通过一些属性告诉 JSON 反序列化器只对 json 进行字符串化的简单方法?
【发布时间】:2020-10-26 20:35:21
【问题描述】:

示例客户端 JSON:

{
   Foo: "Hello!"
   Bar: {
      a: 1,
      b: 2
   }  
}
public class Foobar
{
  public string Foo {get; set;}
  /*[This will come in as a JSON object to the deserializer - just "flatten it" and return the JSON as a string] */
  public string Bar {get; set;
}

预期的伪结果:

Foobar.Foo = "Hello!"
Foobar.Bar = "{a:1, b:2}"

【问题讨论】:

    标签: c# asp.net-mvc .net-core json.net


    【解决方案1】:

    您可以使用Newtonsoft.Json.Linq.JRaw 类型。

    class Foobar
    {
        public string Foo { get; set; }
    
        public JRaw Bar { get; set; }
    }
    

    示例用法:

    var res = JsonConvert.DeserializeObject<Foobar>(yourJsonString);
    var bar = res.Bar.Value.ToString(); // {"a":1,"b":2}
    

    请注意,JRaw.Value 的类型为 object,因此需要 .ToString(),或者,您可以进行转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2021-01-12
      相关资源
      最近更新 更多