我该如何解析这个与.net的json?

问题描述:

如何将此JSON转换为具有两个属性第一个“id”和第二个“答案”的对象列表?我该如何解析这个与.net的json?

[["9","3"],["8","4"],["7","4"],["6","5"],["5","6"],["4","4"],["3","4"]] 
+0

我假设你通过这个JSON对象到Web服务。你在服务器上使用asmx或wcf服务吗? – 2009-10-08 01:33:55

+0

@Ariel Popovsky:是的 – 2009-10-08 10:56:17

下面是使用正则表达式

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("\"", ""))); 
+0

好看的RegEx解决方案,但匹配取决于单个字符的整数。 Yassir的示例数据在这种情况下确实只包含单字符整数,但对于算法的所有运行来说可能并非如此。所以[0-9]匹配需要被替换为\ d(\ d = n长整数) – 2009-10-08 01:35:01

+0

同意,如果需要对正则表达式进行微小更改,可以使其更加灵活。 – 2009-10-08 01:45:29

+0

谢谢你的工作就好:) – 2009-10-08 11:08:11

有101种,但这里有一个.net 2.0字符串解析方法:

 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的字典来保存数据。

+0

看起来不错:) thx – 2009-10-07 23:29:58

+0

不客气。如果你想要更紧凑或更快的算法,我建议使用正则表达式并匹配“,”组。但那不是我可以很快解决的问题。 – 2009-10-07 23:33:14

+0

thx很多,但与正规交易所我会有别的武装! – 2009-10-07 23:40:42

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

在Silverlight中,有一个System.Json.dll让JSON解析非常简单。有一些关于将其纳入.NET4.0的讨论,不知道它是否发生。在常规.NET中,可以使用DataContractJsonSerializer(使用类似List>作为“类型”)。这适用于.NET3.0及以上版本。可能不是所有JSON解析场景的最佳选择(但适用于您的)。

一个非常字面的答案。只会在你指定的格式下工作,如果你传递了意想不到的数据,可能会有点不方便。返回一个KeyValuepair,其中每对都有。

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

需要参考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(); 
    } 
} 

ROFL,HTH

我想工作的easyiest方法如下一段代码:

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); 
     } 
    } 
} 

当然结果包含“列表>”,这是正确的类型你的Json字符串。 你也一定要记得将引用添加到下列DLL:

  • System.Runtime.Serialization
  • System.ServiceModel.Web