[英]Can I use a custom ContractResolver when serializing with Json.Net's JObject.FromObject method?
[英]How can I add a custom root node when serializing an object with JSON.NET?
我已經為我的一些對象添加了一個自定義屬性,如下所示:
[JsonCustomRoot("status")]
public class StatusDTO
{
public int StatusId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
}
屬性非常簡單:
public class JsonCustomRoot :Attribute
{
public string rootName { get; set; }
public JsonCustomRoot(string rootName)
{
this.rootName = rootName;
}
}
序列化對象實例時JSON.NET的默認輸出是:
{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}
現在的問題是: 如何使用自定義屬性的值向JSON添加根節點,如下所示 :
{status:{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}}
我發現有幾篇提到IContractResolver接口的文章,但我無法理解如何做到這一點。 我的嘗試包括這段未完成的代碼:
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
var info = objectType.GetCustomAttributes()
.SingleOrDefault(t => (Type)t.TypeId==typeof(JsonCustomRoot));
if (info != null)
{
var myAttribute = (JsonCustomRoot)info;
// How can i add myAttribute.rootName to the root from here?
// Maybe some other method should be overrided instead?
}
return contract;
}
如果您使用匿名對象怎么辦?
JSON.Serialize(new { status = targetObject});
這是一個專門針對Web API的解決方案,我也在使用它: RootFormatter.cs
我是基於為ASP.NET Web API創建JSONP Formatter而編寫的。
我沒有使用自定義屬性,而是重用JsonObjectAttribute
Title字段。 這是一個使用代碼:
using Newtonsoft.Json
[JsonObject(Title = "user")]
public class User
{
public string mail { get; set; }
}
然后,將RootFormatter添加到App_Start並在WebApiConfig
按如下方式注冊:
GlobalConfiguration.Configuration.Formatters.Insert(0, new RootFormatter());
我能夠獲得類似於WCF的WebMessageBodyStyle.Wrapped
的包裝響應:
{"user":{
"mail": "foo@example.com"
}}
一種非常簡單的方法是將對象放在另一個對象中。 它可能過於簡單化了,但是這在處理集合和單個對象時起作用。
public class StatusDTO
{
public int StatusId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
}
public class statusJasonModel
{
public StatusDTO status { get; set; }
}
現在,如果您將StatusDTO放在statusJsonModel對象中並將其序列化為Json。 它應該給你你想要的答案。
我的一個項目中遇到了類似的挑戰。 以下是我解決問題的步驟。
1.我的實體課程
public class Product
{
[Key]
public string Id { get; set; }
public string Title { get; set; }
public string Album { get; set; }
public string Artist { get; set; }
public string Genre { get; set; }
}
2.創建另一個類,以此形式定義。
public class KindOfMedia
{
public KindOfMedia()
{
Product = new List<Product>();
}
public List<Product> Product { get; set; }
}
3. Web API控制器,它將返回json
public HttpResponseMessage Products()
{
var kind = new KindOfMedia();
kind.Products = new List<Product>();
kind.Products.Add(new Product
{
Id = Guid.NewGuid().ToString(),
Title = "I am A Winner",
Album = "",
Artist = "Project Fame",
Genre = "Contemporal"
});
kind.Products.Add(new Product
{
Id = Guid.NewGuid().ToString(),
Title = "Great Nation",
Album = "Oceans",
Artist = "Timi Dakolo",
Genre = "Gospel"
});
return Request.CreateResponse(HttpStatusCode.OK, kind);
}
4.將此行代碼添加到App_Start文件夾中的WebApi Config文件中
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
請注意, Newtonsoft.Json.PreserveReferencesHandling.None不會保留序列化類型的引用
由此產生的Json是
{
"Musics": [
{
"Id": "bf9faeee-7c39-4c33-a0ea-f60333604061",
"Title": "I am A Winner",
"Album": "",
"Artist": "Project Fame",
"Genre": "Contemporal"
},
{
"Id": "243edd32-7ba2-4ac4-8ab9-bba6399cb0a6",
"Title": "Great Nation",
"Album": "Oceans",
"Artist": "Timi Dakolo",
"Genre": "Gospel"
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.