SerializeObject,URL为根属性

时间:2016-03-21 15:38:41

标签: c# json json.net

我需要将.net对象转换为以下格式:

   {
        "http://www.example.com/extension/powered-by": {
            "name": "Tin Can Engine",
            "homePage": "../lrs-lms/lrs-for-lmss-home/",
            "version": "2012.1.0.5039b"
        }
    }

如何使用JsonConvert.SerializeObject和匿名对象轻松完成此操作?

2 个答案:

答案 0 :(得分:4)

您无法使用匿名对象,因为您无法使用该格式命名的属性。

但是,您可以使用Dictionary<string, object>

Dictionary<string, object> root = new Dictionary<string, object>();
root.Add("http://www.example.com/extension/powered-by", new
{
    name = "Tin Can Engine",
    homePage = "../lrs-lms/lrs-for-lmss-home/",
    version = "2012.1.0.5039b"
});
string json = JsonConvert.SerializeObject(root);

答案 1 :(得分:0)

您可以为Json.NET使用属性名称属性,但不确定这是您要查找的内容。你能尝试下面的课程结构吗?

public class RootObject {
    [JsonProperty(PropertyName = "http://www.example.com/extension/powered-by")]
    public TinCanObject tinCanObject {get;set;}
}

public class TinCanObject {
    public string name {get;set;}
    public string home {get;set;}
    public string version {get;set;}
}
RootObject rootObject = new RootObject();
rootObject.tinCanObject = new TinCanObject();
rootObject.tinCanObject.name = "Tin Can Engine";
rootObject.tinCanObject.home = "../lrs-lms/lrs-for-lmss-home/";
rootObject.tinCanObject.version = "2012.1.0.5039b";

string result = JsonConvert.SerializeObject(rootObject);

希望这有帮助