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



我正在寻找将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]

在列表元组中。。。

任何帮助都将是美妙的。谢谢

这应该可以工作。请注意,您需要通过首先添加括号[]将输入转换为有效的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();

更多信息请参阅文档。

假设您获得了一个有效的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

如果您为Tuple创建了JSON可以解释的数据协定,则可以使用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.
}

相关内容

  • 没有找到相关文章

最新更新