简体   繁体   中英

Combine 2 Serialized json string

Here is how I'm serializing dictionary to 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.

If you use NewtonSoft you will have two methods to override: ReadJson(...) and WriteJson(...), one is for serializing the other for deserializing. 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. When you deserialize that dictionary Json string, your custom code kicks in and you can do whatever you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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