如何使用JavaScriptSerializer将JSON反序列化为元组

时间:2014-08-27 13:17:21

标签: c# json json.net javascriptserializer

我希望将JSON字符串反序列化为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\"}]"

元组列表:

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

我想把它们放在一起

[OkeyTablePaired]:[true]
[OkeyTableIndicator]:[false]
[OkeyTableHued]:[true]
[OkeyTableSpectatorQuiet]:[true]
[OkeyTableEveryoneQuiet]:[true]
List Puple中的

......

任何帮助都会很棒。 感谢。

3 个答案:

答案 0 :(得分:4)

这应该有效。请注意,您需要先通过添加括号[]将输入转换为有效的json数组。您需要获得JSON.NET才能使其发挥作用。

        //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();

documentation中的更多信息。

答案 1 :(得分:2)

假设您获得了一个有效的JSON数组,使用JSON.NET的自定义转换器也可以正常工作:

public class TupleConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<Tuple<string, string>>);
    }

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        List<Tuple<string, string>> result = null;

        if (reader.TokenType == JsonToken.StartArray)
        {            
            JArray deserialized = JArray.Load(reader);
            result = new List<Tuple<string, string>>(deserialized.Count);

            foreach (var token in deserialized)
            {
                if (token.Type == JTokenType.Object)
                {
                    result.Add(Tuple.Create(
                        token["name"].ToObject<string>(),
                        token["value"].ToObject<string>()));
                }
            }
        }

        return result;
    }
}

用法:

List<Tuple<string, string>> result = 
    JsonConvert.DeserializeObject<List<Tuple<string, string>>>(json, new TupleConverter());

示例: https://dotnetfiddle.net/TEbNsH

答案 2 :(得分:1)

如果您为Jup可以解释的Tuple创建了数据协定,则可以使用DataContractJsonSerializer(来自System.Runtime.Serialization.Json库):

var request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "GET";
var jsonSerializer = new DataContractJsonSerializer(typeof (Tuple));
var objResponse = (Tuple) jsonSerializer.ReadObject(response.GetResponseStream());

在您的情况下,数据合同可能非常简单,如下所示:

[DataContract]
public class Tuple
{
    [DataMember]
    public string OkeyTablePaired {get; set;}
    [DataMember]
    public string OkeyTableIndicator {get; set;}
    .....etc.
}