组合2个不相关的JSON对象的方法

时间:2018-12-28 19:58:29

标签: c# json object serialization

假设我有2个对象:

public class CInfo
{
    [JsonProperty(PropertyName = "Id")]
    public string cID { get; set; }

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

public class Event
{
    [JsonProperty(PropertyName = "Time")]
    public DateTime dateTime { get; set; }

    [JsonProperty(PropertyName = "Note")]
    public string comment { get; set; } 
}

函数对返回以下内容:

CInfo cInfo = getCInfo();
List<Event> = getEvents();

这两种方法都打算合并在一起,成为最终的(假设的)对象,需要看起来像这样:

public class CInfoWithEvents
{
    [JsonProperty(PropertyName = "Id")]
    public string cID { get; set; }

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

    [JsonProperty(PropertyName = "Events")]
    public List<Event> { get; set; }
}

这时的目的是做一个JsonConvert.SerialzeObject(CInfoWithEvents),并得到一个代表该最终对象的json字符串。

问题:结合它们的最佳方法是什么?除了创建一个完整的新对象并复制每个属性外,还有一种更优雅的方法,或更糟糕的是:分别序列化cInfoList<Event>并进行某种字符串操作。

谢谢您的时间

1 个答案:

答案 0 :(得分:1)

除了复制两个类的每个属性之外,您还可以通过多种方式实现此目的:

1)将这两个类都添加为第三类的公共财产。

public class CInfoWithEvents
{
    [JsonProperty(PropertyName = "CInfo")]
    public CInfo  {get; set;}

    [JsonProperty(PropertyName = "Events")]
    public List<Event> { get; set; }
}

2)继承CInfo类,并将List作为公共属性。

public class CInfoWithEvents : CInfo
{        
    [JsonProperty(PropertyName = "Events")]
    public List<Event> { get; set; }
}

3)即时创建:

  var javaScriptSerializer = new JavaScriptSerializer();
  var resultJson =  javaScriptSerializer.Serialize(new { CInfo = getCInfo(), Events = getEvents()});

4)使用JObject

    JObject jCInfo = JObject.FromObject(getCInfo());
    jCInfo.Add("Events", JArray.FromObject(getEvents()));
    string json = jCInfo.ToString();