无法使用json.net反序列化json

时间:2021-07-30 17:02:59

This is my first time using json.net and I can't figure it out. Here is my code below.

这是我第一次使用json.net,我无法弄明白。这是我的代码如下。

// Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    private void btnRefreshTweets_Click(object sender, RoutedEventArgs e)
    {
        string ServerURL = @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?text=e&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=&time=&returnCountOnly=false&returnIdsOnly=false&returnGeometry=false&maxAllowableOffset=&outSR=&outFields=&f=json";

        WebClient webClient = new WebClient();
        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
        webClient.DownloadStringAsync(new Uri(ServerURL));
    }

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

    public class Attributes
    {
        public string STATE_NAME { get; set; }
    }

I can't deserialize the STATE_NAME attributes. What am I missing?

我无法反序列化STATE_NAME属性。我错过了什么?

I keep getting this error

我一直收到这个错误

"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[WPJsonSample.MainPage+Attributes]'. Line 1, position 20."

“无法将JSON对象反序列化为类型'System.Collections.Generic.List`1 [WPJsonSample.MainPage + Attributes]'。第1行,第20位。”

3 个解决方案

#1


7  

Here is your class structure ( I used http://json2csharp.com/)

这是你的类结构(我使用过http://json2csharp.com/)

public class FieldAliases
{
    public string STATE_NAME { get; set; }
}

public class Field
{
    public string name { get; set; }
    public string type { get; set; }
    public string alias { get; set; }
    public int length { get; set; }
}

public class Attributes
{
    public string STATE_NAME { get; set; }
}

public class Feature
{
    public Attributes attributes { get; set; }
}

public class RootObject
{
    public string displayFieldName { get; set; }
    public FieldAliases fieldAliases { get; set; }
    public List<Field> fields { get; set; }
    public List<Feature> features { get; set; }
}

#2


3  

The JSON returned from that url is:

从该URL返回的JSON是:

{
  "displayFieldName": "STATE_NAME",
  "fieldAliases": {
    "STATE_NAME": "STATE_NAME"
  },
  "fields": [
    {
      "name": "STATE_NAME",
      "type": "esriFieldTypeString",
      "alias": "STATE_NAME",
      "length": 25
    }
  ],
  "features": [
    {
      "attributes": {
        "STATE_NAME": "Maine"
      }
  }
}

So, we can see here the root is an object, not an enumerable like a List<>

所以,我们可以看到root是一个对象,而不是像List <>这样的可枚举

You'll have to fix the class structure to match the JSON, or access it with Linq queries (there are some samples of this in the json.net website).

您必须修复类结构以匹配JSON,或使用Linq查询访问它(在json.net网站中有一些这样的示例)。

#3


3  

IF you are trying to hit that endpoint, you should not be manually submitting the query, you should use the ArcGIS WP7 SDK (it's FREE!). Then use the QueryTask.

如果您尝试命中该端点,则不应手动提交查询,应使用ArcGIS WP7 SDK(它是免费的!)。然后使用QueryTask。

(if you just need help with parsing JSON, see below)

(如果您只需要解析JSON的帮助,请参阅下文)

    QueryTask queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/");
    queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
    queryTask.Failed += QueryTask_Failed;

    ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query();
    query.Text = "e";
    query.ReturnGeometry = false;

    queryTask.ExecuteAsync(query);


private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
{
    FeatureSet featureSet = args.FeatureSet
    // use the featureSet to do something. It contains everything you need
}

If for whatever reason, you do not want to use the QueryTask, you can still use the FromJson method of the FeatureSet

如果由于某种原因,您不想使用QueryTask,您仍然可以使用FeatureSet的FromJson方法

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var featureSet = ESRI.ArcGIS.Client.Tasks.FeatureSet.FromJson(e.Result);
    // Use it
}

If you need help with JSON, here are some key concepts.

如果您需要有关JSON的帮助,请参阅以下一些关键概念。

1) Curly braces represent an object

1)花括号代表一个物体

2) square brackets represent an array.

2)方括号代表一个数组。

3) properties are separated by commas

3)属性用逗号分隔

When using JSON.NET, you should add the JsonProperty attribute to a property. This way you can maintain proper names even if the json sucks

使用JSON.NET时,应将JsonProperty属性添加到属性中。这样即使json很糟糕,你也可以维护正确的名字

[JsonProperty("STATE_NAME")]
public string StateName { get; set; }

#1


7  

Here is your class structure ( I used http://json2csharp.com/)

这是你的类结构(我使用过http://json2csharp.com/)

public class FieldAliases
{
    public string STATE_NAME { get; set; }
}

public class Field
{
    public string name { get; set; }
    public string type { get; set; }
    public string alias { get; set; }
    public int length { get; set; }
}

public class Attributes
{
    public string STATE_NAME { get; set; }
}

public class Feature
{
    public Attributes attributes { get; set; }
}

public class RootObject
{
    public string displayFieldName { get; set; }
    public FieldAliases fieldAliases { get; set; }
    public List<Field> fields { get; set; }
    public List<Feature> features { get; set; }
}

#2


3  

The JSON returned from that url is:

从该URL返回的JSON是:

{
  "displayFieldName": "STATE_NAME",
  "fieldAliases": {
    "STATE_NAME": "STATE_NAME"
  },
  "fields": [
    {
      "name": "STATE_NAME",
      "type": "esriFieldTypeString",
      "alias": "STATE_NAME",
      "length": 25
    }
  ],
  "features": [
    {
      "attributes": {
        "STATE_NAME": "Maine"
      }
  }
}

So, we can see here the root is an object, not an enumerable like a List<>

所以,我们可以看到root是一个对象,而不是像List <>这样的可枚举

You'll have to fix the class structure to match the JSON, or access it with Linq queries (there are some samples of this in the json.net website).

您必须修复类结构以匹配JSON,或使用Linq查询访问它(在json.net网站中有一些这样的示例)。

#3


3  

IF you are trying to hit that endpoint, you should not be manually submitting the query, you should use the ArcGIS WP7 SDK (it's FREE!). Then use the QueryTask.

如果您尝试命中该端点,则不应手动提交查询,应使用ArcGIS WP7 SDK(它是免费的!)。然后使用QueryTask。

(if you just need help with parsing JSON, see below)

(如果您只需要解析JSON的帮助,请参阅下文)

    QueryTask queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/");
    queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
    queryTask.Failed += QueryTask_Failed;

    ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query();
    query.Text = "e";
    query.ReturnGeometry = false;

    queryTask.ExecuteAsync(query);


private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
{
    FeatureSet featureSet = args.FeatureSet
    // use the featureSet to do something. It contains everything you need
}

If for whatever reason, you do not want to use the QueryTask, you can still use the FromJson method of the FeatureSet

如果由于某种原因,您不想使用QueryTask,您仍然可以使用FeatureSet的FromJson方法

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var featureSet = ESRI.ArcGIS.Client.Tasks.FeatureSet.FromJson(e.Result);
    // Use it
}

If you need help with JSON, here are some key concepts.

如果您需要有关JSON的帮助,请参阅以下一些关键概念。

1) Curly braces represent an object

1)花括号代表一个物体

2) square brackets represent an array.

2)方括号代表一个数组。

3) properties are separated by commas

3)属性用逗号分隔

When using JSON.NET, you should add the JsonProperty attribute to a property. This way you can maintain proper names even if the json sucks

使用JSON.NET时,应将JsonProperty属性添加到属性中。这样即使json很糟糕,你也可以维护正确的名字

[JsonProperty("STATE_NAME")]
public string StateName { get; set; }