1

I'm trying to parse to the following json string with NewtonSoft json 4.5:

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

My objects that i will serialize to json looks like this:

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; }
}

I've tried to set the property name to empty but it doesnt solve the issue.

Henrik
  • 1,797
  • 4
  • 22
  • 46
  • Possible duplicate of [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/questions/40480489/json-net-serialize-deserialize-property-as-a-value-not-as-an-object) – dbc Jun 16 '17 at 01:41

1 Answers1

2

You should replace List<GrandChild> with List<string> or else add a custom JsonConverter for GrandChild like so.

[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() };
    }
}
TylerBrinkley
  • 1,066
  • 10
  • 16