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

本文关键字:序列化 json 字符串 属性 追加 | 更新日期: 2023-09-27 18:25:52

我有一个要序列化的类

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。我怎样才能达到同样的目的?

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

首先,在DesignEntity类中再添加一个字段。其类型是从中序列化designDetailsjson的协定类。

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

哇!

更新

如果您不能访问从中序列化designDetailsjson的类,那么您有两个选项。

  1. 尝试从json结构推导类,并自己创建DesignDetailsObject(推荐)
  2. 手动附加json字符串(如果需要,我会尝试向您展示如何)-如果类真的很重,并且不值得这么做,则必须应用此方法

选项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);