72

在我的网络应用程序中,我使用 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 库中有任何属性或其他方式吗?

4

10 回答 10

41

使用匿名类

使用匿名类以您想要的方式塑造您的模型:

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

string json = JsonConvert.SerializeObject(root);
于 2013-04-30T08:03:38.247 回答
38

我找到了一种简单的方法来呈现它...只需声明一个动态对象并将动态对象中的第一项分配为您的集合类...此示例假设您使用的是 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"}, {...}]}
于 2013-06-06T02:55:26.980 回答
13

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

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();
}
于 2013-04-30T08:31:04.637 回答
7

对不起,我的英语不是那么好。但我喜欢改进投票的答案。我认为使用 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
         ]
      ]
   }
}
于 2018-06-15T21:30:24.460 回答
4
string Json = JsonConvert.SerializeObject(new Car { Name = "Ford", Owner = "John Smith" }, Formatting.None);

对于根元素,使用 GlobalConfiguration。

于 2013-04-30T08:14:04.270 回答
4

对我来说一个非常简单的方法就是创建 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"
    }
  ]
}

希望这可以帮助!

于 2016-09-28T01:47:34.330 回答
3

好吧,您至少可以告诉 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”属性的开头。

这不完全是您正在寻找的东西,但在面对类似问题时对我来说已经足够了。

于 2015-08-03T19:18:20.370 回答
2

编写自定义JsonConverter是类似问题中提到的另一种方法。但是,由于JsonConverter设计方式的性质,对这个问题使用这种方法很棘手,因为您需要小心WriteJson实现以避免陷入无限递归:JSON.Net 在使用 [JsonConvert()] 时会抛出 StackOverflowException

一种可能的实现:

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();
}
于 2020-02-26T16:46:24.697 回答
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();
于 2015-10-12T10:25:32.110 回答
-5
[Newtonsoft.Json.JsonObject(Title = "root")]
public class TestMain

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

于 2015-11-18T04:30:40.443 回答