代码之家  ›  专栏  ›  技术社区  ›  Hannoun Yassir

如何用.net解析这个json?

  •  1
  • Hannoun Yassir  · 技术社区  · 15 年前

    如何将此JSON转换为具有两个属性(第一个是“id”,第二个是“answer”)的对象列表?

    [["9","3"],["8","4"],["7","4"],["6","5"],["5","6"],["4","4"],["3","4"]]
    
    7 回复  |  直到 15 年前
        1
  •  5
  •   Igor Zevaka    15 年前

    我开始使用JSON.NET- http://james.newtonking.com/pages/json-net.aspx . 它是一个非常全面的JSON库,允许您做几乎任何事情。

        2
  •  5
  •   Rubens Farias    15 年前

    System.Web.Extensions 装配

    using System.Linq;
    using System.Collections;
    using System.Collections.Generic;
    using System.Web.Script.Serialization;
    
    class Program
    {
        public class Test
        {
            public string Id { get; set; }
            public string Answer { get; set; }
        }
    
        static void Main(string[] args)
        {
            string data ="[[\"9\",\"3\"],[\"8\",\"4\"],[\"7\",\"4\"],[\"6\",\"5\"]]";
            List<Test> tests = 
                Array.ConvertAll<ArrayList, Test>(
                    new JavaScriptSerializer()
                        .Deserialize<ArrayList>(data)
                            .OfType<ArrayList>().ToArray(), 
                   (item) =>
                   {
                       return new Test()
                       {
                           Id = (string)item[0],
                           Answer = (string) item[1]
                       };
                   }).ToList();
        }
    }
    

    罗夫,HTH

        3
  •  2
  •   Paul Sasik    15 年前

            Dictionary<int, int> jsonValues = new Dictionary<int, int>();
    
            string data = "[[\"9\",\"3\"],[\"8\",\"4\"],[\"7\",\"4\"],[\"6\",\"5\"],[\"5\",\"6\"],[\"4\",\"4\"],[\"3\",\"4\"]]";
    
            string[] items = data.Split(new string[]{"\"],[\""}, StringSplitOptions.RemoveEmptyEntries);
    
            foreach (string str in items)
            {
                string[] intVals = str
                    .Replace("\"", "")
                    .Replace("[", "")
                    .Replace("[", "")
                    .Replace("]", "").Split(',');
    
                jsonValues.Add(int.Parse(intVals[0]), int.Parse(intVals[1]));
            }
    
            // test print:
            foreach (KeyValuePair<int,int> kvp in jsonValues)
            {
                System.Diagnostics.Debug.WriteLine(
                    "ID:" + kvp.Key + " val:" + kvp.Value );
            }
    

    顺便说一句因为您正在提取名称-值对,所以我只使用int/int字典来保存数据。

        4
  •  1
  •   Gregory    15 年前

            var val = "[[\"9\",\"3\"],[\"8\",\"4\"],[\"7\",\"4\"],[\"6\",\"5\"],[\"5\",\"6\"],[\"4\",\"4\"],[\"3\",\"4\"]]";
    
            var result = val.ToCharArray()
                .Where(itm => Char.IsDigit(itm))
                .Select((itm, index) => new {c = int.Parse(itm.ToString()),index = index + 1})
                .GroupBy(itm => itm.index % 2 == 0 ? itm.index - 1 : itm.index)
                .Select(itm => new KeyValuePair<int, int>(itm.ElementAt(0).c, itm.ElementAt(1).c));
    
        5
  •  1
  •   Carlos Muñoz Boom    15 年前

    我认为最简单的方法是以下代码:

    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;
    
    namespace JsonParser
    {
        class Program
        {
            static void Main(string[] args)
            {
                string data = "[[\"9\",\"3\"],[\"8\",\"4\"],[\"7\",\"4\"],[\"6\",\"5\"],[\"5\",\"6\"],[\"4\",\"4\"],[\"3\",\"4\"]]";
                var stream = new MemoryStream(new ASCIIEncoding().GetBytes(data));
                var deserializer = new DataContractJsonSerializer(typeof(List<List<string>>));
                var result = (List<List<string>>)deserializer.ReadObject(stream);
            }
        }
    }
    

    此外,您还必须记住添加对以下DLL的引用:

    • System.ServiceModel.Web
        6
  •  0
  •   Roatin Marth    15 年前

    下面是一个使用RegEx的解决方案

    string data = "[[\"9\",\"3\"],[\"8\",\"4\"],[\"7\",\"4\"],[\"6\",\"5\"],[\"5\",\"6\"],[\"4\",\"4\"],[\"3\",\"4\"]]";
    
    var pairs = (from Match m in Regex.Matches(data, "\"[0-9]\"\\,\"[0-9]\"") 
                 select m.Value.Split(',')).ToDictionary(d => d[0], d => d[1]);
    

    添加:如果希望结果值为int而不是字符串,则可以这样做

    var pairs = (from Match m in Regex.Matches(data, "\"[0-9]\"\\,\"[0-9]\"") 
            select m.Value.Split(','))
           .ToDictionary(d => Int32.Parse(d[0].Replace("\"", "")), 
                         d => Int32.Parse(d[1].Replace("\"", "")));
    
        7
  •  0
  •   Eugene Osovetsky    15 年前

    在Silverlight中,有System.Json.dll使Json解析非常容易。有人说要把它放到.NET4.0中,但不确定它是否发生过。