在 Windows Phone c# 中解析 JSON

Posted

技术标签:

【中文标题】在 Windows Phone c# 中解析 JSON【英文标题】:Parsing JSON in Windows Phone c# 【发布时间】:2012-06-05 12:02:50 【问题描述】:

我对 json 和 c# 有点陌生,我正在尝试从 api 收集一些数据。 json数据的部分链接为:https://data.cityofchicago.org/api/views/*REMOVED*/rows.json?search=rahm&jsonp=? 而且给出的数据有点乱:


  "meta" : 
    "view" : 
      "id" : "xzkq-xp2w",
      "name" : "Current Employee Names, Salaries, and Position Titles",
      "attribution" : "City of Chicago",
      "attributionLink" : "http://www.cityofchicago.org",
      "averageRating" : 0,
      "category" : "Administration & Finance",
      "createdAt" : 1317154735,
      "description" : "This dataset is a listing of all current City of Chicago employees, complete with full names, departments, positions, and annual salaries. For hourly employees the annual salary is estimated. Data Owner: Human Resources. Frequency: Data is updated quarterly. Last Updated: April 19, 2012. For information on the positions and related salaries detailed in the budget as of January 1, 2012, visit the \"Budget - Positions and Salaries in 2012 Appropriation Ordinance\" dataset: http://bit.ly/twq5oO",
      "displayType" : "table",
      "downloadCount" : 4033,
      "numberOfComments" : 0,
      "oid" : 538938,
      "publicationAppendEnabled" : false,
      "publicationDate" : 1334860835,
      "publicationGroup" : 241512,
      "publicationStage" : "published",
      "rowClass" : "",
      "rowsUpdatedAt" : 1334860755,
      "rowsUpdatedBy" : "scy9-9wg4",
      "searchString" : "rahm",
      "signed" : false,
      "tableId" : 300029,
      "totalTimesRated" : 0,
      "viewCount" : 48059,
      "viewLastModified" : 1334860836,
      "viewType" : "tabular",
      "columns" : [ 
        "id" : -1,
        "name" : "sid",
        "dataTypeName" : "meta_data",
        "fieldName" : "sid",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "id",
        "dataTypeName" : "meta_data",
        "fieldName" : "id",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "position",
        "dataTypeName" : "meta_data",
        "fieldName" : "position",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "created_at",
        "dataTypeName" : "meta_data",
        "fieldName" : "created_at",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "created_meta",
        "dataTypeName" : "meta_data",
        "fieldName" : "created_meta",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "updated_at",
        "dataTypeName" : "meta_data",
        "fieldName" : "updated_at",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "updated_meta",
        "dataTypeName" : "meta_data",
        "fieldName" : "updated_meta",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : -1,
        "name" : "meta",
        "dataTypeName" : "meta_data",
        "fieldName" : "meta",
        "position" : 0,
        "renderTypeName" : "meta_data",
        "format" : 
        
      , 
        "id" : 6676081,
        "name" : "Name",
        "dataTypeName" : "text",
        "fieldName" : "name",
        "position" : 1,
        "renderTypeName" : "text",
        "tableColumnId" : 1532233,
        "width" : 148,
        "cachedContents" : 
          "non_null" : 32925,
          "smallest" : "AARON,  ELVIA J",
          "null" : 0,
          "largest" : "ZYSKOWSKI,  DARIUSZ",
          "top" : [ 
            "count" : 20,
            "item" : "ZYSKO,  RICHARD"
          , 
            "count" : 19,
            "item" : "ZYSKOWSKI,  DARIUSZ"
           ]
        ,
        "format" : 
        
      , 
        "id" : 6676082,
        "name" : "Position Title",
        "dataTypeName" : "text",
        "fieldName" : "job_titles",
        "position" : 2,
        "renderTypeName" : "text",
        "tableColumnId" : 1532235,
        "width" : 220,
        "cachedContents" : 
          "non_null" : 32925,
          "smallest" : "A/MGR COM SVC-ELECTIONS",
          "null" : 0,
          "largest" : "ZONING PLAN EXAMINER",
          "top" : [ 
            "count" : 20,
            "item" : "POLICE OFFICER"
          , 
            "count" : 19,
            "item" : "FIREFIGHTER"
          , 
            "count" : 18,
            "item" : "MOTOR TRUCK DRIVER"
          , 
            "count" : 17,
            "item" : "SANITATION LABORER"
          , 
            "count" : 16,
            "item" : "FIREFIGHTER-EMT"
          , 
            "count" : 15,
            "item" : "POLICE OFFICER (ASSIGNED AS DETECTIVE)"
          , 
            "count" : 14,
            "item" : "SERGEANT"
          , 
            "count" : 13,
            "item" : "CROSSING GUARD"
          , 
            "count" : 12,
            "item" : "TRAFFIC CONTROL AIDE-HOURLY"
          , 
            "count" : 11,
            "item" : "POOL MOTOR TRUCK DRIVER"
          , 
            "count" : 10,
            "item" : "CONSTRUCTION LABORER"
          , 
            "count" : 9,
            "item" : "FIREFIGHTER/PARAMEDIC"
          , 
            "count" : 8,
            "item" : "LIBRARIAN I"
          , 
            "count" : 7,
            "item" : "OPERATING ENGINEER-GROUP C"
          , 
            "count" : 6,
            "item" : "PARAMEDIC"
          , 
            "count" : 5,
            "item" : "FRM OF MACHINISTS - AUTOMOTIVE"
          , 
            "count" : 4,
            "item" : "ELECTRICAL MECHANIC"
          , 
            "count" : 3,
            "item" : "SENIOR PUBLIC INFORMATION OFFICER"
          , 
            "count" : 2,
            "item" : "LEGAL SECRETARY"
          , 
            "count" : 1,
            "item" : "AIRPORT OPERATIONS SUPVSR I"
           ]
        ,
        "format" : 
          "align" : "left"
        
      , 
        "id" : 6676083,
        "name" : "Department",
        "dataTypeName" : "text",
        "fieldName" : "department",
        "position" : 3,
        "renderTypeName" : "text",
        "tableColumnId" : 1532236,
        "width" : 183,
        "cachedContents" : 
          "non_null" : 32925,
          "smallest" : "ADMIN HEARNG",
          "null" : 0,
          "largest" : "WATER MGMNT",
          "top" : [ 
            "count" : 20,
            "item" : "WATER MGMNT"
          , 
            "count" : 19,
            "item" : "POLICE"
          , 
            "count" : 18,
            "item" : "GENERAL SERVICES"
          , 
            "count" : 17,
            "item" : "FIRE"
          , 
            "count" : 16,
            "item" : "FAMILY & SUPPORT"
          , 
            "count" : 15,
            "item" : "STREETS & SAN"
          , 
            "count" : 14,
            "item" : "FINANCE"
          , 
            "count" : 13,
            "item" : "BUSINESS AFFAIRS"
          , 
            "count" : 12,
            "item" : "OEMC"
          , 
            "count" : 11,
            "item" : "TRANSPORTN"
          , 
            "count" : 10,
            "item" : "HEALTH"
          , 
            "count" : 9,
            "item" : "AVIATION"
          , 
            "count" : 8,
            "item" : "LAW"
          , 
            "count" : 7,
            "item" : "PUBLIC LIBRARY"
          , 
            "count" : 6,
            "item" : "ADMIN HEARNG"
          , 
            "count" : 5,
            "item" : "CULTURAL AFFAIRS"
          , 
            "count" : 4,
            "item" : "COMMUNITY DEVELOPMENT"
          , 
            "count" : 3,
            "item" : "BUILDINGS"
          , 
            "count" : 2,
            "item" : "CITY COUNCIL"
          , 
            "count" : 1,
            "item" : "CITY CLERK"
           ]
        ,
        "format" : 
        
      , 
        "id" : 6676084,
        "name" : "Employee Annual Salary",
        "dataTypeName" : "money",
        "fieldName" : "employee_annual_salary",
        "position" : 4,
        "renderTypeName" : "money",
        "tableColumnId" : 1532237,
        "width" : 161,
        "cachedContents" : 
          "non_null" : 32925,
          "smallest" : "0.96",
          "sum" : "2475198578.40",
          "null" : 0,
          "average" : "75176.87405922551",
          "largest" : "260004.00",
          "top" : [ 
            "count" : 20,
            "item" : "75372.00"
          , 
            "count" : 19,
            "item" : "78012.00"
          , 
            "count" : 18,
            "item" : "80724.00"
          , 
            "count" : 17,
            "item" : "70408.00"
          , 
            "count" : 16,
            "item" : "68203.20"
          , 
            "count" : 15,
            "item" : "83706.00"
          , 
            "count" : 14,
            "item" : "73216.00"
          , 
            "count" : 13,
            "item" : "18886.40"
          , 
            "count" : 12,
            "item" : "84032.00"
          , 
            "count" : 11,
            "item" : "86840.00"
          , 
            "count" : 10,
            "item" : "61530.00"
          , 
            "count" : 9,
            "item" : "83982.00"
          , 
            "count" : 8,
            "item" : "99648.00"
          , 
            "count" : 7,
            "item" : "87324.00"
          , 
            "count" : 6,
            "item" : "62796.00"
          , 
            "count" : 5,
            "item" : "100048.00"
          , 
            "count" : 4,
            "item" : "62916.00"
          , 
            "count" : 3,
            "item" : "87372.00"
          , 
            "count" : 2,
            "item" : "84760.00"
          , 
            "count" : 1,
            "item" : "89772.80"
           ]
        ,
        "format" : 
          "precisionStyle" : "standard",
          "noCommas" : "false",
          "align" : "right"
        
       ],
      "grants" : [ 
        "inherited" : false,
        "type" : "viewer",
        "flags" : [ "public" ]
       ],
      "metadata" : 
        "custom_fields" : 
          "Metadata" : 
            "Last Updated Date via Automated Load" : "",
            "Time Period" : "Last Updated April 19, 2012",
            "Data Owner" : "Human Resources",
            "Frequency" : "Data is updated quarterly"
          
        ,
        "renderTypeConfig" : 
          "visible" : 
            "table" : true
          
        ,
        "availableDisplayTypes" : [ "table", "fatrow", "page" ],
        "rdfSubject" : "0",
        "filterCondition" : 
          "value" : "AND",
          "children" : [ 
            "value" : "OR",
            "type" : "operator",
            "metadata" : 
              "includeAuto" : 15,
              "tableColumnId" : 
                "241512" : 1532236
              ,
              "operator" : "EQUALS"
            
           ],
          "type" : "operator",
          "metadata" : 
            "unifiedVersion" : 2,
            "advanced" : true
          
        ,
        "rowIdentifier" : "0",
        "rdfClass" : ""
      ,
      "owner" : 
        "id" : "vi9p-p863",
        "displayName" : "Eric Phillips",
        "emailUnsubscribed" : false,
        "privacyControl" : "login",
        "profileLastModified" : 1333412533,
        "roleName" : "administrator",
        "screenName" : "Eric Phillips",
        "rights" : [ "create_datasets", "edit_others_datasets", "edit_sdp", "edit_site_theme", "moderate_comments", "manage_users", "chown_datasets", "edit_nominations", "approve_nominations", "feature_items", "federations", "manage_stories", "manage_approval", "change_configurations", "view_domain", "view_others_datasets", "edit_pages", "create_pages" ]
      ,
      "query" : 
      ,
      "rights" : [ "read" ],
      "tableAuthor" : 
        "id" : "vi9p-p863",
        "displayName" : "Eric Phillips",
        "emailUnsubscribed" : false,
        "privacyControl" : "login",
        "profileLastModified" : 1333412533,
        "roleName" : "administrator",
        "screenName" : "Eric Phillips",
        "rights" : [ "create_datasets", "edit_others_datasets", "edit_sdp", "edit_site_theme", "moderate_comments", "manage_users", "chown_datasets", "edit_nominations", "approve_nominations", "feature_items", "federations", "manage_stories", "manage_approval", "change_configurations", "view_domain", "view_others_datasets", "edit_pages", "create_pages" ]
      ,
      "tags" : [ "personnel" ],
      "flags" : [ "default" ]
    
  ,
  "data" : [ [ 8172, "56A29995-E979-411D-BE47-27F48FD1A0A1", 8172, 1334860745, "386464", 1334860745, "386464", "\n", "EMANUEL,  RAHM", "MAYOR", "MAYOR'S OFFICE", "216210.00" ]
 ]

现在我正在尝试获取特定人员的薪水,即 216210,它位于“数据”列表的最后一行。

这就是我现在拥有的:

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        
            if (e.Error != null)
            
                return;
            
            List<Employee> emp = JsonConvert.DeserializeObject<List<Employee>>(e.Result);
            this.lbTweets.ItemsSource = emp;
        
    

    public class Employee
    


        [JsonProperty("data")]
        public string salary
        
            get;
            set;
        

    

我猜我没有正确的[JsonProperty("data")] 部分,单击按钮后出现此错误:

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll

Additional information: Unexpected character encountered while parsing value: ?. Line 0, position 0.

有人可以帮忙吗?谢谢

编辑: 不确定这是否有帮助,但我用这段代码在 javascript 中解析了它:

$.getJSON(this.query, function(response) 
        var i, results;
        results = [];
        for (i = 0; i < response.data.length; i += 1) 
            row =  
                name: response.data[i][8],
                salary: response.data[i][11]
            
            results.push(row);
        

更新:在仅将链接设为 json 请求而不是 jsonp 请求后,新的 json 不再包含任何额外字符。但我收到一个新错误:附加信息:无法将 JSON 对象反序列化为类型“System.Collections.Generic.List`1[WPJsonSample.Tweet]”。第 2 行,位置 11。

我使用 json2csharp 为我生成类,所以我有这个类:

public class RootObject

    public Meta meta  get; set;  // removed this line because I only want the data
    public List<List<object>> data  get; set; 

但是我仍然从上面得到那个错误,可能是我没有正确的数据类型:

List<RootObject> tweets = JsonConvert.DeserializeObject<List<RootObject>>(e.Result);

【问题讨论】:

错误报告意外字符“?”,如果在尝试调用 DeserializeObject 之前从 JSON 字符串的开头删除此字符,是否有帮助? json uri 中包含了那个问号,不知道如何删除它。 你能在字符串 "e.Result.Replace("?", string.empty)" 上调用 Replace 来看看这是否有帮助吗? 没有工作,给出了这个错误:附加信息:解析值时遇到意外字符:(。第 0 行,位置 0。 尝试删除 '(' 还有 ')' 和 ';'人物也是。理想情况下,json 对象包含在 或 [] 【参考方案1】:

你真的需要使用 JSONP 吗? http://en.wikipedia.org/wiki/JSONP

这个 url 是否更适合获取和反序列化一个简单的 JSON 对象? https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json?search=rahm

通过使用 JSONP(例如“ajax 跨域请求”),最后需要一个回调函数: https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json?search=rahm&jsonp=callbackfunc (使用 jquery 的 JSONP 请求每次都会添加一个唯一的回调函数)。

【讨论】:

感谢您的发现,我之前在 javascript 中使用了它,忘记删除它,但我收到了一个新错误:附加信息:无法将 JSON 对象反序列化为“System.Collections.Generic”类型。列表`1[Chicago.Tweet]'。第 2 行,位置 11。 是的,这是反序列化、强类型对象和集合的常见问题。我让你做一些研究,因为我不知道你的对象的定义。对此有很多讨论(***.com/questions/2546138/…)。请记住,对于反序列化列表,您需要一个列表(作为 JSON 数组)。这可能会帮助您更快地创建 C# 对象:json2csharp.com

以上是关于在 Windows Phone c# 中解析 JSON的主要内容,如果未能解决你的问题,请参考以下文章

使用 facebook c# sdk 在 windows phone 8 应用程序中没有从 facebook 获得登录响应

在 Windows Phone 7 中解析 XML

windows phone 8.1 调用rest api c#

如何在 Windows phone silverlight 应用程序上从 C# 填充视频

计算点击次数并显示在另一个页面上[Windows Phone c#]

如何使用`this解析C#(Windows Phone)中的JSONData。