Search code examples
c#jsonjson.netjavascriptserializer

How to Deserialize JSON with JavaScriptSerializer to Tuples


I'm looking way to Deserialize JSON string to c# List<Tuple<string, string>>.

    "[{\"name\":\"OkeyTablePaired\",\"value\":\"true\"},    
      {\"name\":\"OkeyTableIndicator\",\"value\":\"true\"},    
      {\"name\":\"OkeyTableHued\",\"value\":\"true\"},    
      {\"name\":\"OkeyTableSpectatorQuiet\",\"value\":\"true\"},    
      {\"name\":\"OkeyTableEveryoneQuiet\",\"value\":\"true\"}]"

Tuple List:

List<Tuple<string, string>> tupleJson = new List<Tuple<string, string>>();

I would like to put them together as

[OkeyTablePaired]:[true]
[OkeyTableIndicator]:[false]
[OkeyTableHued]:[true]
[OkeyTableSpectatorQuiet]:[true]
[OkeyTableEveryoneQuiet]:[true]

in the List Tuple...

Any help would be fantastic. Thanks.


Solution

  • This should work. Note that you need to convert the input to valid json array by adding brackets [] first. You will need to get JSON.NET to make this work.

            //using System;
            //using System.Collections.Generic;
            //using System.Linq;
            //using Newtonsoft.Json.Linq;
    
            string validJson = "[" + json + "]";
            JArray jsonArray = JArray.Parse(validJson);
            List<Tuple<string, string>> tupleJson = jsonArray
                .Select(p => new Tuple<string, string>((string)p["name"], (string)p["value"]))
                .ToList();
    

    More info in the documentation.