将属性附加到c#中的序列化json字符串

时间:2015-12-07 07:54:45

标签: c# json serialization

我有一个我要序列化的课程

public class DesignEntity
{
    public string DesignName { get; set; }
    public string DesignID { get; set; }
    [ScriptIgnore]
    public string designDetails { get; set; }
}

属性designDetails已包含序列化数据,因此无需再次序列化

DesignEntity designSessionEntity = null;
JavaScriptSerializer jSerializer = null;
string designJsonSession = "null";

designSessionEntity = new DesignEntity();
jSerializer = new JavaScriptSerializer();

designSessionEntity = /* */ // Get Values via some method
designJsonSession = jSerializer.Serialize(designSessionEntity); 
// Now append designDetails to resultant string json

我想在序列化完成后将designDetails附加到designJsonSession。我怎样才能实现同样的目标?

1 个答案:

答案 0 :(得分:2)

首先,在DesignEntity课程中再添加一个字段。其类型是designDetails json序列化的契约类。

public class DesignEntity
{
    public string DesignName { get; set; }
    public string DesignID { get; set; }
    /// new field
    public DesignDetailsObject DesignDetails { get; set; }
    [ScriptIgnore]
    public string designDetails { get; set; }
}

然后,像往常一样获取对象,首先将json反序列化为新字段,然后序列化。

var designSessionEntity = new DesignEntity();
var jSerializer = new JavaScriptSerializer();

designSessionEntity = /// Get Values via some method

/// assign the design details with deserialized object
designSessionEntity.DesignDetails = jSerializer.Deserialize<DesignDetailsObject>(designSessionEntity.designDetails);

/// serialize it again
var designJsonSession = jSerializer.Serialize(designSessionEntity); 

瞧!

<强>更新

如果您无法访问designDetails json序列化的类,那么您有两种选择。

  1. 尝试从json结构中推断出类,并自己创建DesignDetailsObject(推荐)。
  2. 手动附加json字符串(我将尝试向您展示如何使用) - 如果课程非常繁重,则必须应用此方法,并且不值得工作。
  3. 代码段对于选项2:

    public string JsonAppender ( string targetJson, List<string> fields, object value )
    {
        var insertIndex = 0;
        foreach ( var field in fields )
        {
            var _fieldDescriptor = field + "\":";
            insertIndex += targetJson.Substring(insertIndex).IndexOf(_fieldDescriptor) + _fieldDescriptor.Length;
        }
    
        var lengthOfDefaultVal = targetJson.Substring(insertIndex).IndexOf("\"") - 1;
    
        return targetJson.Substring(0, insertIndex) + "\"" + value + "\"" + targetJson.Substring(insertIndex + lengthOfDefaultVal);
    }
    

    用法:

    var fieldAppendedJson = JsonAppender(json, new List<string> { "designDetails " }, designSessionEntity.designDetails);