【问题标题】:Skip property name and only use the value in json跳过属性名称,仅使用 json 中的值
【发布时间】:2017-06-15 08:29:56
【问题描述】:

我正在尝试使用 NewtonSoft json 4.5 解析为以下 json 字符串:

{
   "Name":"Henrik", 
   "Children":[
   {
      "Name":"Adam",
      "Grandchildren":[
         "Jessica", //How can i only show the value and not the property name?
         "Michael"
      ]
   }
   ]
}

我将序列化为 json 的对象如下所示:

public class Parent
{
   public string Name { get; set; }

   [JsonProperty(PropertyName = "Children")]
   public List<Child> Childs { get; set; }
}

public class Child {
   public string Name { get; set; }

   [JsonProperty(PropertyName = "Grandchildren")]
   public List<GrandChild> GrandChilds { get; set; }
}

public class GrandChild {
   [JsonProperty(PropertyName = "")]
   public string Name { get; set; }
}

我尝试将属性名称设置为空,但它并没有解决问题。

【问题讨论】:

标签: json.net


【解决方案1】:

您应该将List&lt;GrandChild&gt; 替换为List&lt;string&gt;,或者像这样为GrandChild 添加一个自定义JsonConverter

[JsonConverter(typeof(GrandChildConverter))]
public class GrandChild
{
    public string Name { get; set; }
}

public class GrandChildConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(GrandChild);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((GrandChild)value).Name);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new GrandChild { Name = reader.Value.ToString() };
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2021-05-27
    • 1970-01-01
    • 2012-11-17
    相关资源
    最近更新 更多