0

我正在使用 json.net

将json反序列化为对象后,我想获取该对象的json源

例如

objParent:{
  objChild1: {name:"testObj"},
  objChild2: {age: 25}
}

在 C# 代码中

public ObjChild1
{
  public string name {get;set;}

  [JsonIgnore]
  public string JsonSource { get; set; }    //objChild1: {name:"testObj"}
}

public ObjChild2
{
  public int age {get;set;}

  [JsonIgnore]
  public string JsonSource { get; set; }   //objChild2: {age: 25}   
}
4

1 回答 1

0

我没有安装 json.net,但是使用标准类,您可以简单地将单个对象序列化回 JSON 字符串,如下所示:

...
    public static class JSONHelper
    {
        public static string ToJSONString(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }
    }
...

    public ObjChild1
    {
        public string name {get;set;}

        [ScriptIgnore]
        public string JsonSource { get { return this.ToJSONString(); } }
    }    

    public class ObjChild2
    {
        public int age {get;set;}

        [ScriptIgnore]
        public string JsonSource { get { return this.ToJSONString(); } }
    }
于 2013-03-27T17:31:42.350 回答