C# Parse JSON response(从响应中获取特定部分)
C# Parse JSON response (Get a specific part from response)
我正在尝试从 JSON 响应字符串中获取特定部分。
这是 JSON 代码:
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "door",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"homographNumber": "000",
"senses": [
{
"definitions": [
"a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"
],
"id": "m_en_gbus0290920.005",
"subsenses": [
{
"definitions": [
"a doorway"
],
"id": "m_en_gbus0290920.008"
},
{
"definitions": [
"used to refer to the distance from one building in a row to another"
],
"id": "m_en_gbus0290920.009"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"text": "door"
}
],
"type": "headword",
"word": "door"
}
]
}
我正在尝试获取此代码
"definitions": [
"a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"
在一个字符串中
这是我的代码:
string language = "en";
string word_id = textBox1.Text.ToLower();
String url = "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id+"/definitions";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Add("app_id", app_Id);
client.DefaultRequestHeaders.Add("app_key", app_Key);
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
var s = JsonConvert.DeserializeObject(result);
textBox2.Text = s.ToString();
}
else MessageBox.Show(response.ToString());
我正在使用 C#。
C#类
第一步是创建一些 类 以允许我们在 C# 中表示数据。如果你没有它们... QuickType does that.
namespace QuickType
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class GettingStarted
{
[JsonProperty("metadata")]
public Metadata Metadata { get; set; }
[JsonProperty("results")]
public Result[] Results { get; set; }
}
public partial class Result
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("lexicalEntries")]
public LexicalEntry[] LexicalEntries { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("word")]
public string Word { get; set; }
}
public partial class LexicalEntry
{
[JsonProperty("entries")]
public Entry[] Entries { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("lexicalCategory")]
public string LexicalCategory { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
public partial class Entry
{
[JsonProperty("homographNumber")]
public string HomographNumber { get; set; }
[JsonProperty("senses")]
public Sense[] Senses { get; set; }
}
public partial class Sense
{
[JsonProperty("definitions")]
public string[] Definitions { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subsenses")]
public Subsense[] Subsenses { get; set; }
}
public partial class Subsense
{
[JsonProperty("definitions")]
public string[] Definitions { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
public partial class Metadata
{
[JsonProperty("provider")]
public string Provider { get; set; }
}
public partial class GettingStarted
{
public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
}
反序列化
您会注意到我们还为我们生成了用于序列化和反序列化的转换器。反序列化位很简单:
var result = JsonConvert.DeserializeObject<GettingStarted>(json);
使用
从 result
变量开始,使用点找到您的项目...
var description = result.results.lexicalEntries.First()
.entries.First()
.senses.First()
.definitions.First();
所有这些 First()
调用都是由于数据的每个部分都是数组。为此,您需要参考 System.Linq
。如果您在这些级别中的任何级别有多个或少于一个,您将需要阅读一些关于该怎么做的内容(您可能需要使用集合,或执行更多遍历)。
您可以创建一个 class,其属性是您尝试解析的 JSON 的名称。这样你就可以将 JSON 反序列化为 class 的一个实例并提取你需要的任何 属性 。您需要使用 Newtonsoft.Json 包。
示例class:
public class YourClass
{
public string propertyA { get; set; }
public string propertyB { get; set; }
}
然后在你的主代码中:
YourClass yourClass = new YourClass();
try
{
yourClass = JsonConvert.DeserializeObject<YourClass>(yourJsonStringGoesHere);
}
catch (Exception ex)
{
//log exception here
}
我正在尝试从 JSON 响应字符串中获取特定部分。
这是 JSON 代码:
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "door",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"homographNumber": "000",
"senses": [
{
"definitions": [
"a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"
],
"id": "m_en_gbus0290920.005",
"subsenses": [
{
"definitions": [
"a doorway"
],
"id": "m_en_gbus0290920.008"
},
{
"definitions": [
"used to refer to the distance from one building in a row to another"
],
"id": "m_en_gbus0290920.009"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"text": "door"
}
],
"type": "headword",
"word": "door"
}
]
}
我正在尝试获取此代码
"definitions": [ "a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"
在一个字符串中 这是我的代码:
string language = "en";
string word_id = textBox1.Text.ToLower();
String url = "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id+"/definitions";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Add("app_id", app_Id);
client.DefaultRequestHeaders.Add("app_key", app_Key);
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
var s = JsonConvert.DeserializeObject(result);
textBox2.Text = s.ToString();
}
else MessageBox.Show(response.ToString());
我正在使用 C#。
C#类
第一步是创建一些 类 以允许我们在 C# 中表示数据。如果你没有它们... QuickType does that.
namespace QuickType
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class GettingStarted
{
[JsonProperty("metadata")]
public Metadata Metadata { get; set; }
[JsonProperty("results")]
public Result[] Results { get; set; }
}
public partial class Result
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("lexicalEntries")]
public LexicalEntry[] LexicalEntries { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("word")]
public string Word { get; set; }
}
public partial class LexicalEntry
{
[JsonProperty("entries")]
public Entry[] Entries { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("lexicalCategory")]
public string LexicalCategory { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
public partial class Entry
{
[JsonProperty("homographNumber")]
public string HomographNumber { get; set; }
[JsonProperty("senses")]
public Sense[] Senses { get; set; }
}
public partial class Sense
{
[JsonProperty("definitions")]
public string[] Definitions { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subsenses")]
public Subsense[] Subsenses { get; set; }
}
public partial class Subsense
{
[JsonProperty("definitions")]
public string[] Definitions { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
public partial class Metadata
{
[JsonProperty("provider")]
public string Provider { get; set; }
}
public partial class GettingStarted
{
public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
}
反序列化
您会注意到我们还为我们生成了用于序列化和反序列化的转换器。反序列化位很简单:
var result = JsonConvert.DeserializeObject<GettingStarted>(json);
使用
从 result
变量开始,使用点找到您的项目...
var description = result.results.lexicalEntries.First()
.entries.First()
.senses.First()
.definitions.First();
所有这些 First()
调用都是由于数据的每个部分都是数组。为此,您需要参考 System.Linq
。如果您在这些级别中的任何级别有多个或少于一个,您将需要阅读一些关于该怎么做的内容(您可能需要使用集合,或执行更多遍历)。
您可以创建一个 class,其属性是您尝试解析的 JSON 的名称。这样你就可以将 JSON 反序列化为 class 的一个实例并提取你需要的任何 属性 。您需要使用 Newtonsoft.Json 包。
示例class:
public class YourClass
{
public string propertyA { get; set; }
public string propertyB { get; set; }
}
然后在你的主代码中:
YourClass yourClass = new YourClass();
try
{
yourClass = JsonConvert.DeserializeObject<YourClass>(yourJsonStringGoesHere);
}
catch (Exception ex)
{
//log exception here
}