简体   繁体   English

组合2个序列化的json字符串

[英]Combine 2 Serialized json string

Here is how I'm serializing dictionary to JSON:这是我将字典序列化为 JSON 的方式:

Dictionary<string, string> dictFormValues = new Dictionary<string, string>();
Dictionary<string, string> hsContext = new Dictionary<string, string>();

dictFormValues.Add("firstname", "Name");
dictFormValues.Add("lastname", "LastName");
dictFormValues.Add("email", "Email");

hsContext.Add("ipAddress", "ip");
hsContext.Add("pageUrl", "url");
hsContext.Add("pageName", "Title");

System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

string strFormContentJSON = json.Serialize(dictFormValues); //First JSON
string strHubSpotContextJSON = json.Serialize(hsContext); //Second JSON

How can I combine those 2 together where they will look like below:我如何将这两个组合在一起,它们将如下所示:

var data = {
  "fields": [
    {
      "name": "firstname",
      "value": "Name"
    },
    {
      "name": "lastname",
      "value": "LastName"
    },
    {
      "name": "email",
      "value": "Email"
    }        
  ],
  "context": {
    "ipAddress": "ip",
    "pageUri": "url",
    "pageName": "Title"
  }
}

I tried something like this but I don't know if this is even right:我试过这样的事情,但我不知道这是否正确:

string strPostData = "";

strPostData = json.Serialize(new { OneDetails = strFormContentJSON, TwoDetails = strHubSpotContextJSON });

If you want to get that exact format the only way would be to write a custom JsonConverter.如果您想获得该确切格式,唯一的方法是编写自定义 JsonConverter。

If you use NewtonSoft you will have two methods to override: ReadJson(...) and WriteJson(...), one is for serializing the other for deserializing.如果您使用 NewtonSoft,您将有两种方法可以覆盖:ReadJson(...) 和 WriteJson(...),一种用于序列化,另一种用于反序列化。 That way you can write you own code responsible for serializing and deserializing.这样您就可以编写自己的代码来负责序列化和反序列化。

In your case you can merge the two dictionaries into one and transform that into a Json string.在您的情况下,您可以将两个字典合并为一个并将其转换为 Json 字符串。 When you deserialize that dictionary Json string, your custom code kicks in and you can do whatever you want.当您反序列化该字典 Json 字符串时,您的自定义代码就会启动,您可以随心所欲。

Check NewtonSoft docs for this: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm检查 NewtonSoft 文档: https ://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

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

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