简体   繁体   English

有没有一种方法可以序列化Dictionary <string, string> 有一个内在的对象?

[英]Is there a way to serialize Dictionary<string, string> with an inner object?

I have next dictionary 我有下一本字典

 var invoiceParams = new Dictionary<string, string>();
 invoiceParams.Add("order_id", "111");
 invoiceParams.Add("goods", "[{amount:100, count: 2}]");

 var jsonString = JsonConvert.SerializeObject(invoiceParams);

Can I serialize it into next JSON with newtonsoft.json? 我可以使用newtonsoft.json将其序列化为下一个JSON吗?

{
   "order_id":111,
   "goods":[
      {
         "amount":100,
         "count":2
      }
   ]
}

Why not just make it an object? 为什么不仅仅使其成为对象?

 var invoiceParams = new Dictionary<string, string>();
 invoiceParams.Add("order_id", "111");
 invoiceParams.Add("goods", new List<object>(){ new {amount=100, count=2}});
 var jsonString = JsonConvert.SerializeObject(invoiceParams);

When I want to output data as JSON, I normally used Named Types. 当我想将数据输出为JSON时,通常使用命名类型。 By which I mean plain old C# classes that represent the data structure. 我的意思是表示数据结构的普通C#类。 They're a good option because they can be used to deserialize the data as well as serialize it. 它们是一个很好的选择,因为它们可用于反序列化数据以及序列化数据。 In fact my data models usually sit in a Class Library project all of their own so any producers or consumers can reuse them as needed. 实际上,我的数据模型通常都位于类库项目中,因此任何生产者或消费者都可以根据需要重用它们。 Another advantage is that you can put Attributes on the Properties , which is useful for customizing JSON.Net. 另一个优点是您可以将Attributes放在Properties上 ,这对于自定义JSON.Net很有用。

If I'm feeling a bit more lacking in effort (read: lazy) and don't need the deserialization benefits then sometimes I'll use Anonymous Types . 如果我觉得自己需要更多的精力(阅读:懒惰)并且不需要反序列化的好处,那么有时我会使用Anonymous Types You can create a new Type "on the fly" so to speak which is the format you want to output as. 可以说,您可以“即时”创建新的Type,这是您要输出的格式。

Here's an example of using Anonymous Types to reformat the data during output. 这是在输出过程中使用匿名类型重新格式化数据的示例。

This is the code working on DotNet Fiddle: https://dotnetfiddle.net/wLkoLk 这是在DotNet Fiddle上运行的代码: https : //dotnetfiddle.net/wLkoLk

This is the code itself: 这是代码本身:

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var data = new
        {
            order_id = "111",
            isTrue = true,
            rating = 3,
            goods = 
            new []
            {
                new
                {
                    amount = 100,
                    count = 2
                },
                new
                {
                    amount = 9001,
                    count = 1
                }
            }
        };

        var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings() { Formatting = Formatting.Indented });

        Console.WriteLine(json);
    }
}

And here's the JSON output: 这是JSON输出:

{
  "order_id": "111",
  "isTrue": true,
  "rating": 3,
  "goods": [
    {
      "amount": 100,
      "count": 2
    },
    {
      "amount": 9001,
      "count": 1
    }
  ]
}

So what does the Named Type approach look like? 那么“命名类型”方法是什么样的?

Here's the working DotNet Fiddle: https://dotnetfiddle.net/d7sJua 这是工作中的DotNet小提琴: https : //dotnetfiddle.net/d7sJua

Here's the code: 这是代码:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class Invoice
{
    [JsonProperty("order_id")]  
    public string OrderId { get;set;}

    public List<Good> Goods { get;set;}
}

public class Good
{
    public int Amount { get;set;}
    public int Count { get;set;}
}

public class Program
{   
    public static void Main()
    {
        var invoice = new Invoice()
        {
            OrderId = "111",
            Goods = new List<Good>()
            {
                new Good()
                {
                    Amount = 100,
                    Count = 2
                }
            }
        };

        var json = JsonConvert.SerializeObject(invoice, new JsonSerializerSettings()
        {
            Formatting = Formatting.Indented,
            ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        Console.WriteLine(json);
    }
}

And the JSON output: 以及JSON输出:

{
  "order_id": "111",
  "goods": [
    {
      "amount": 100,
      "count": 2
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM