Json.NET使用根名称序列化对象

时间:2013-04-30 07:58:36

标签: c# asp.net .net json json.net

在我的网络应用程序中,我使用的是Newtonsoft.Json,我有以下对象

[Newtonsoft.Json.JsonObject(Title = "MyCar")]
public class Car
{
    [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
    public string Name{get;set;}

    [Newtonsoft.Json.JsonProperty(PropertyName = "owner")]
    public string Owner{get;set;}
}

我希望用根名称(类名)序列化它们。这是使用

所需的格式
{'MyCar':
 {
   'name': 'Ford',
   'owner': 'John Smith'
 }
}

我知道我可以用匿名对象做到这一点,但是在Newtonsoft.Json库中有任何属性或其他方式吗?

10 个答案:

答案 0 :(得分:32)

使用匿名类

使用匿名类以您希望的方式塑造模型:

var root = new 
{ 
    car = new 
    { 
        name = "Ford", 
        owner = "Henry"
    }
};

string json = JsonConvert.SerializeObject(root);

答案 1 :(得分:32)

我发现了一种简单的方法来渲染它...只需声明一个动态对象并将动态对象中的第一项指定为您的集合类...此示例假设您使用的是Newtonsoft.Json

private class YourModelClass
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

var collection = new List<YourModelClass>();

var collectionWrapper = new {

    myRoot = collection

};

var output = JsonConvert.SerializeObject(collectionWrapper);

你最终应该得到的是:

{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}

答案 2 :(得分:9)

您可以轻松创建自己的序列化程序

var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);

string Serialize<T>(T o)
{
    var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;

    var jv = JValue.FromObject(o);

    return new JObject(new JProperty(attr.Title, jv)).ToString();
}

答案 3 :(得分:4)

string Json = JsonConvert.SerializeObject(new Car { Name = "Ford", Owner = "John Smith" }, Formatting.None);

表示根元素使用GlobalConfiguration。

答案 4 :(得分:3)

对我来说,一个非常简单的方法就是创建2个类。

public class ClassB
{
    public string id{ get; set; }
    public string name{ get; set; }
    public int status { get; set; }
    public DateTime? updated_at { get; set; }
}

public class ClassAList
{
    public IList<ClassB> root_name{ get; set; } 
}

当你要进行序列化时:

var classAList = new ClassAList();
//...
//assign some value
//...
var jsonString = JsonConvert.SerializeObject(classAList)

最后,您将看到所需的结果如下:

{
  "root_name": [
    {
      "id": "1001",
      "name": "1000001",
      "status": 1010,
      "updated_at": "2016-09-28 16:10:48"
    },
    {
      "id": "1002",
      "name": "1000002",
      "status": 1050,
      "updated_at": "2016-09-28 16:55:55"
    }
  ]
}

希望这有帮助!

答案 5 :(得分:2)

抱歉,我的英语不太好。但我喜欢改善赞成的答案。 我认为使用Dictionary更简单,更干净。

class Program
    {
        static void Main(string[] args)
        {
            agencia ag1 = new agencia()
            {
                name = "Iquique",
                data = new object[] { new object[] {"Lucas", 20 }, new object[] {"Fernando", 15 } }
            };
            agencia ag2 = new agencia()
            {
                name = "Valparaiso",
                data = new object[] { new object[] { "Rems", 20 }, new object[] { "Perex", 15 } }
            };
            agencia agn = new agencia()
            {
                name = "Santiago",
                data = new object[] { new object[] { "Jhon", 20 }, new object[] { "Karma", 15 } }
            };


            Dictionary<string, agencia> dic = new Dictionary<string, agencia>
            {
                { "Iquique", ag1 },
                { "Valparaiso", ag2 },
                { "Santiago", agn }
            };

            string da = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            Console.WriteLine(da);
            Console.ReadLine();
        }


    }

    public class agencia
    {
        public string name { get; set; }
        public object[] data { get; set; }
    }

此代码生成以下json(这是所需的格式)

{  
   "Iquique":{  
      "name":"Iquique",
      "data":[  
         [  
            "Lucas",
            20
         ],
         [  
            "Fernando",
            15
         ]
      ]
   },
   "Valparaiso":{  
      "name":"Valparaiso",
      "data":[  
         [  
            "Rems",
            20
         ],
         [  
            "Perex",
            15
         ]
      ]
   },
   "Santiago":{  
      "name":"Santiago",
      "data":[  
         [  
            "Jhon",
            20
         ],
         [  
            "Karma",
            15
         ]
      ]
   }
}

答案 6 :(得分:1)

好吧,你至少可以告诉Json.NET包含类型名称:http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htmNewtonsoft.Json.JsonSerializer jser = new Newtonsoft.Json.JsonSerializer(); jser.TypeNameHandling = TypeNameHandling.Objects;

该类型将包含在对象的“$ type”属性的开头。

这并不是你想要的,但面对同样的问题对我来说已经足够了。

答案 7 :(得分:1)

我希望这有帮助。

//Sample of Data Contract:

[DataContract(Name="customer")]
internal class Customer {
  [DataMember(Name="email")] internal string Email { get; set; }
  [DataMember(Name="name")] internal string Name { get; set; }
}

//This is an extension method useful for your case:

public static string JsonSerialize<T>(this T o)
{
  MemoryStream jsonStream = new MemoryStream();
  var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
  serializer.WriteObject(jsonStream, o);

  var jsonString = System.Text.Encoding.ASCII.GetString(jsonStream.ToArray());

  var props = o.GetType().GetCustomAttributes(false);
  var rootName = string.Empty;
  foreach (var prop in props)
  {
    if (!(prop is DataContractAttribute)) continue;
    rootName = ((DataContractAttribute)prop).Name;
    break;
  }
  jsonStream.Close();
  jsonStream.Dispose();

  if (!string.IsNullOrEmpty(rootName)) jsonString = string.Format("{{ \"{0}\": {1} }}", rootName, jsonString);
  return jsonString;
}

//Sample of usage

var customer = new customer { 
Name="John",
Email="john@domain.com"
};
var serializedObject = customer.JsonSerialize();

答案 8 :(得分:1)

编写自定义JsonConverter是类似问题中提到的另一种方法。但是,由于JsonConverter的设计性质,对于该问题使用该方法非常棘手,因为您需要谨慎使用WriteJson实现,以免陷入无限递归:JSON.Net throws StackOverflowException when using [JsonConvert()]

一种可能的实现方式:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    //JToken t = JToken.FromObject(value); // do not use this! leads to stack overflow
    JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());

    writer.WriteStartObject();
    writer.WritePropertyName(value.GetType().Name);
    writer.WriteStartObject();
    foreach (var property in contract.Properties)
    {
        // this removes any property with null value
        var propertyValue = property.ValueProvider.GetValue(value);
        if (propertyValue == null) continue;

        writer.WritePropertyName(property.PropertyName);
        serializer.Serialize(writer, propertyValue);
        //writer.WriteValue(JsonConvert.SerializeObject(property.ValueProvider.GetValue(value))); // this adds escaped quotes
    }
    writer.WriteEndObject();
    writer.WriteEndObject();
}

答案 9 :(得分:-5)

[Newtonsoft.Json.JsonObject(Title = "root")]
public class TestMain

这是您需要添加以使代码正常运行的唯一属性。