使用json.net发出序列化C#类的问题 [英] Issue serializeing C# class with json.net

查看:72
本文介绍了使用json.net发出序列化C#类的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的朋友,我道歉我是全新的消费/生产JSON,并且是json.net的首次使用者。我有一个RequestDetails类,其中包含下面示例JSON中列出的值{Requester}到{EMAILS_TO_NOTIFY}。基本上,我想从添加请求生成请求。我可以很好地序列化类,但是,我希望json.net添加父操作详细信息部分,而不在RequestDetails类之上创建其他空白嵌套类但我我对如何继续有点迷茫。



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.

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",
       }
   }
}





我尝试过:



我已经搜索了一下,但我现在太无知了,因为我害怕找到适当的搜索条件。我确实试图调查一个自定义的JsonConverter只是为了将我的数据包装在父节中,但我没有成功,我不确定这是正确的方向。任何帮助将不胜感激。



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.

推荐答案

好看后我更相信我想要做的更好,因为我想将我的对象包装在多个嵌套属性中(JProperty)。如果有更好/更清洁的方法来实现这一点,请告诉我,但现在这样做。



使用我的基本抽象类的属性

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
[JsonConverter(typeof(InputDataBaseConverter))]





然后按如下方式创建自定义转换器:





and then creating a custom converter as follows:

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


这篇关于使用json.net发出序列化C#类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆