Shaun
Shaun

Reputation: 3895

One-off Nested JSON Property

I'm interfacing with an API that has a request containing this snippet:

     "occurrence":{  
        "type":"XYZ"
     }

Instead of creating an Occurence object with a member Type, is there some Newtonsoft JSON magic that can serialize

  public string Occurence = "XYZ"

into the format above?

Upvotes: 1

Views: 120

Answers (1)

Eric Damtoft
Eric Damtoft

Reputation: 1423

You could use a custom JsonConverter to essentially flatten the JSON representation of the occurrence property into just the type.

class SomeModel
{
  [JsonConverter(typeof(OccuranceConverter))]
  public string Occurence { get; set; }
}

class OccuranceConverter : JsonConverter<string>
{
  public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
  {
    var json = JObject.Load(reader);
    return json.GetValue("type").Value<string>();
  }

  public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
  {
    var json = new JObject { ["type"] = value };
    json.WriteTo(writer);
  }
}

Upvotes: 3

Related Questions