我有一个我要序列化的课程
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
。我怎样才能实现同样的目标?
答案 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序列化的类,那么您有两种选择。
DesignDetailsObject
(推荐)。代码段对于选项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);