2012-12-24 188 views
4

我有一个看起来像这样JSON数据:提取数据

{ 
    "position":[ 
     { 
     "top":[ 
      42, 
      12 
     ] 
     }, 
     { 
     "middle":[ 
      10, 
      15 
     ] 
     }, 
     { 
     "bottom":[ 
      5, 
      201 
     ] 
     }, 
     { 
     "axis":[ 
      { 
       "X":[ 
        901, 
        51, 
        67 
       ] 
      }, 
      { 
       "Y":[ 
        1474186, 
        561647 
       ] 
      }, 
      { 
       "Z":[ 
        911, 
        1296501 
       ] 
      }, 
      15, 
      20 
     ] 
     } 
    ], 
    "validated":true, 
    "metadata":{ 
     "uri":"/data/complex/", 
     "session":[ 
     1818, 
     14 
     ], 
     "private":false 
    }, 
    "vists":0, 
    "ok":true, 
    "data":{ 
     "10":{ 
     "title":"Alpha", 
     "author":"Justin X. Ample", 
     "cover":"/f48hf58.tiff" 
     }, 
     "901":{ 
     "title":"Tau", 
     "author":"Felina Blank", 
     "cover":"/45trthrref.tiff" 
     } 
    }, 
    "live":null 
} 

从这个数据我想显示像这样的列表:

Alpha, Justin X. Ample 
Tau, Felina Blank 

注意,钥匙(在我的例子中,10和901)是不可预测的。所以我想以某种方式创建一个代表“数据”结构的对象,并迭代它以获取每个条目的标题和作者。

有了一个基本的JSON结构,我有这样的事情成功(使用JSON.NET):

public class Foo 
    { 
     public int bar { get; set; } 
     public string baz { get; set; } 
     public string quxx { get; set; } 
    } 

... 

// json = {"bar": 1, "baz":"two", "quxx":"three"} 
var result = await JsonConvert.DeserializeObjectAsync<Foo>(json); 

return result.baz // "two" 

但我想不出什么,我需要做的,使之具有复杂结构的工作。

+1

如果您使用Visual Studio 2012,得到[ASP.NET和Web Tools 2012.2(http://go.microsoft.com/fwlink/?LinkID=275131)。它有一个名为“将JSON粘贴为类”的功能,它将从剪贴板中的JSON生成一个C#类。 – Oded

回答

6
var jObj = JsonConvert.DeserializeObject(json) as JObject; 
var result = jObj["data"].Children() 
       .Cast<JProperty>() 
       .Select(x => new { 
        Title = (string)x.Value["title"] , 
        Author = (string)x.Value["author"], 
       }) 
       .ToList(); 
1

您可以像以前一样使用它。你只需要修改你的实体类如下:

public class MyVeryVeryUsefulObject 
{ 

    public Position[] position { get; set; } 
    public string baz { get; set; } 
    public string quxx { get; set; } 
} 

public class Position 
{ 
    public Int32[] top; 
    public Int32[] middle; 
    public Int32[] bottom; 
} 

等等。您只需在代码中将JSON对象表示为实体类。

前段时间我发现了一个有用的链接,也许这会减少你实现这个json结构的工作量。 http://json2csharp.com/