Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ok folks, I apologize I am brand new consuming/producing JSON in general and a first time user of json.net. I have a class "RequestDetails" that contains the values {Requester} through {EMAILS_TO_NOTIFY} listed in the example JSON below. Basically, I want to generate the request from Add request. I can serialize the class fine but, I would like json.net to add the parent operation and Details "sections" without creating otherwise blank nested classes above my RequestDetails class but I am a bit lost on how to proceed.

C#
public class RequestDetails
{
    [JsonProperty("REQUESTER")]
    public string Requester { get; set; }
    [JsonProperty("SUBJECT")]
    public string Subject { get; set; }
    [JsonProperty("REQUESTTEMPLATE")]
    public string RequestTemplate { get; set; }
    [JsonProperty("PRIORITY")]
    public string Priority { get; set; }
    [JsonProperty("LEVEL")]
    public string Level { get; set; }
    [JsonProperty("IMPACT")]
    public string Impact { get; set; }
    [JsonProperty("URGENCY")]
    public string Urgency { get; set; }
    [JsonProperty("DESCRIPTION")]
    public string Description { get; set; }
    [JsonProperty("ATTACHMENT_IDS")]
    public IList<string> AttachmentIds { get; set; }
    [JsonProperty("UDF_CHAR1")]
    public string UdfChar1 { get; set; }
    [JsonProperty("UDF_LONG1")]
    public string UdfLong1 { get; set; }
    [JsonProperty("UDF_DATE1")]
    public string UdfDate1 { get; set; }
    [JsonProperty("EMAILS_TO_NOTIFY")]
    public string EmailsToNotify { get; set; }
}



{
   "operation": {
      "Details": {
         "REQUESTER": "Howard Stern",        
         "SUBJECT": "Subject of the request",
         "REQUESTTEMPLATE": "Default Request",
         "PRIORITY": "High",
         "LEVEL": "Tier 1",
         "IMPACT": "Affects Business",
         "URGENCY": "High",
         "DESCRIPTION": "Mail Server is down",
         "ATTACHMENT_IDS": ["1005","1006"],
         "UDF_CHAR1": "Test",
         "UDF_LONG1": "1001",
         "UDF_DATE1": "90080098767654"
         "EMAILS_TO_NOTIFY"  : "howard.stern@zillum.com",
       }
   }
}


What I have tried:

I have googled around a bit but I'm too ignorant right now to have proper terms to search by I'm afraid. I did attempt to look into a custom JsonConverter just to 'wrap' my data inside the parent sections but I wasn't successful and I'm uncertain that is the right direction. Any assistance would be appreciated.
Posted
Updated 21-Nov-17 21:20pm

1 solution

Ok after looking into this more I believe what I wanted to do is better stated as I wanted to wrap my object inside multiple nested properties (JProperty). If there is a better/cleaner way of accomplishing this please let me know but this does the trick for now.

using a attribute on my base abstract class of
C#
[JsonConverter(typeof(InputDataBaseConverter))]


and then creating a custom converter as follows:

C#
public class InputDataBaseConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var operation = new JObject();
        var details = new JObject();
        var main = new JObject();

        var type = value.GetType();

        foreach (var prop in type.GetProperties())
        {
            if (!prop.CanRead) continue;
            var propVal = prop.GetValue(value, null);

            if (propVal != null)
                main.Add(prop.Name, JToken.FromObject(propVal, serializer));
            else if(serializer.NullValueHandling == NullValueHandling.Include)
                main.Add(prop.Name, JToken.FromObject("null", serializer));
        }

        operation.AddFirst(new JProperty("Details", main));
        details.AddFirst(new JProperty("operation",operation));
        details.WriteTo(writer);
    }

    /// <summary>
    /// Gets a value indicating whether this <see cref="T:Newtonsoft.Json.JsonConverter"/> can read JSON.
    /// </summary>
    /// <value>
    /// <c>true</c> if this <see cref="T:Newtonsoft.Json.JsonConverter"/> can read JSON; otherwise, <c>false</c>.
    /// </value>
    public override bool CanRead { get; } = false;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new Exception("Not Needed");
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof (InputDataBase));
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900