获取 Json 属性 其中名称包含一些字符串
Get Json property which name contains some string
我没有典型的 json,当我用用户名请求配置文件时(例如,我展示了如果我用 username1
查询会是什么)。如果我用 username2
查询那么 属性 名字是 "field_set_key=\"profile\",username=\"username2\""
"UserProfileResource": {
"field_set_key=\"profile\",username=\"username1\"": {
"data": {
"profile": {
...
}
}
}
}
我不能简单地用一些名称设置 JsonProperty
,因为它是动态的。所以我需要以某种方式手动解析它。
是的,如果我知道请求的配置文件(传递的用户名),这看起来很简单。
刚刚将 json 字符串解析为一些 JObject
,构建动态 属性 名称并使用 LINQ to JSON.
获取其值
但是如果我不知道请求的用户名怎么办?我可以使用上面提到的 LINQ to JSON 作为示例来获取 属性 值,该名称包含一些字符串(如 field_set_key=\"profile\"
)吗?
您好,我在一个旧项目中找到了这段代码,希望它能帮助您解决一些问题!
(这用于使用 google 映射 API 自动填充地址)
我将此作为答案发布,因为我无法发表评论,因为有 50 reputation:P
//Get all adress components based on street-name & house-number
public static List<Address> PostalcodeResults(string streetname, string number)
{
//Request url
string url = @"https://maps.googleapis.com/maps/api/geocode/json?address=" + streetname + " " + number + "&result_type=street_address&key=" + API_Key;
//Webrequest-streamreader
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
// json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();
//Create lists for the results from the request
JObject googleSearch = JObject.Parse(responseFromServer);
IList<JToken> results = googleSearch["results"].Children().ToList();
//list to return
List<Address> list = new List<Address>();
//foreach result
foreach (JToken Result in results)
{
//Some local variable
string street = "";
string house_number = "";
string zipcode = "";
string country = "";
string place = "";
string provincie = "";
string Township = "";
//Foreach adress component from result
foreach (JToken Adress_Components in Result.First().First())
{
//List with types
IList<JToken> types = Adress_Components["types"].Children().ToList();
//Foreach type
foreach (JToken type in types)
{
//determ witch Variable it is
if (type.ToString() == "route")
street = Adress_Components["long_name"].ToString();
else if (type.ToString() == "street_number")
house_number = Adress_Components["long_name"].ToString();
else if (type.ToString() == "postal_code")
zipcode = Adress_Components["long_name"].ToString();
else if (type.ToString() == "country")
country = Adress_Components["long_name"].ToString();
else if (type.ToString() == "locality")
place = Adress_Components["long_name"].ToString();
else if (type.ToString() == "administrative_area_level_1")
provincie = Adress_Components["long_name"].ToString();
else if (type.ToString() == "administrative_area_level_2")
Township = Adress_Components["long_name"].ToString();
}
}
//MessageBox.Show(" Street: " + street + "\n House nr: " + house_number + "\n Zipcode: " + zipcode + "\n Country: " + country + "\n Place: " + place + "\n Province: " + provincie + "\n Township: " + Township);
list.Add(new Address(street, house_number, zipcode, country, place, provincie, Township));
}
//return the lists
return list;
}
//Get directions from one point to another
private void getdirections()
{
string API_Key = "apikey";
string url = @"https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=" + API_Key;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
// json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();
//richTextBox1.Text = responseFromServer;
}
}
json 回复:
"results" : [
{
"address_components" : [
{
"long_name" : "Somepostalcode",
"short_name" : "Somepostalcode",
"types" : [ "postal_code" ]
},
{
"long_name" : "Somelocality",
"short_name" : "Somelocality",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Someadministrative_area_level_2",
"short_name" : "Someadministrative_area_level_2",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "SOmeProvince",
"short_name" : "SomeShortname",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "SomeCountry",
"short_name" : "SomeCountryShortage",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "foratted adress",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : ,
"lng" :
},
"southwest" : {
"lat" : ,
"lng" :
}
},
"location" : {
"lat" : ,
"lng" :
},
"location_type" : "",
"viewport" : {
"northeast" : {
"lat" : ,
"lng" :
},
"southwest" : {
"lat" : ,
"lng" :
}
}
},
"place_id" : "",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
正如@ZoharPeled 在评论中所说,我可以使用 JsonPath to query json using SelectToken As shown in Querying JSON with SelectToken
var jObject = JObject.Parse(json);
var userProfile = jObject.SelectToken("UserProfileResource.*.data.profile").ToObject<UserProfile>();
在示例中,我将我的 json 解析为 JObject
,然后使用 SelectToken
从中解析 select 配置文件数据。如您所见,我也在那里使用了 JSONPath 表达式。
*
表示
wildcard. All objects/elements regardless their names.
我没有典型的 json,当我用用户名请求配置文件时(例如,我展示了如果我用 username1
查询会是什么)。如果我用 username2
查询那么 属性 名字是 "field_set_key=\"profile\",username=\"username2\""
"UserProfileResource": {
"field_set_key=\"profile\",username=\"username1\"": {
"data": {
"profile": {
...
}
}
}
}
我不能简单地用一些名称设置 JsonProperty
,因为它是动态的。所以我需要以某种方式手动解析它。
是的,如果我知道请求的配置文件(传递的用户名),这看起来很简单。
刚刚将 json 字符串解析为一些 JObject
,构建动态 属性 名称并使用 LINQ to JSON.
但是如果我不知道请求的用户名怎么办?我可以使用上面提到的 LINQ to JSON 作为示例来获取 属性 值,该名称包含一些字符串(如 field_set_key=\"profile\"
)吗?
您好,我在一个旧项目中找到了这段代码,希望它能帮助您解决一些问题! (这用于使用 google 映射 API 自动填充地址) 我将此作为答案发布,因为我无法发表评论,因为有 50 reputation:P
//Get all adress components based on street-name & house-number
public static List<Address> PostalcodeResults(string streetname, string number)
{
//Request url
string url = @"https://maps.googleapis.com/maps/api/geocode/json?address=" + streetname + " " + number + "&result_type=street_address&key=" + API_Key;
//Webrequest-streamreader
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
// json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();
//Create lists for the results from the request
JObject googleSearch = JObject.Parse(responseFromServer);
IList<JToken> results = googleSearch["results"].Children().ToList();
//list to return
List<Address> list = new List<Address>();
//foreach result
foreach (JToken Result in results)
{
//Some local variable
string street = "";
string house_number = "";
string zipcode = "";
string country = "";
string place = "";
string provincie = "";
string Township = "";
//Foreach adress component from result
foreach (JToken Adress_Components in Result.First().First())
{
//List with types
IList<JToken> types = Adress_Components["types"].Children().ToList();
//Foreach type
foreach (JToken type in types)
{
//determ witch Variable it is
if (type.ToString() == "route")
street = Adress_Components["long_name"].ToString();
else if (type.ToString() == "street_number")
house_number = Adress_Components["long_name"].ToString();
else if (type.ToString() == "postal_code")
zipcode = Adress_Components["long_name"].ToString();
else if (type.ToString() == "country")
country = Adress_Components["long_name"].ToString();
else if (type.ToString() == "locality")
place = Adress_Components["long_name"].ToString();
else if (type.ToString() == "administrative_area_level_1")
provincie = Adress_Components["long_name"].ToString();
else if (type.ToString() == "administrative_area_level_2")
Township = Adress_Components["long_name"].ToString();
}
}
//MessageBox.Show(" Street: " + street + "\n House nr: " + house_number + "\n Zipcode: " + zipcode + "\n Country: " + country + "\n Place: " + place + "\n Province: " + provincie + "\n Township: " + Township);
list.Add(new Address(street, house_number, zipcode, country, place, provincie, Township));
}
//return the lists
return list;
}
//Get directions from one point to another
private void getdirections()
{
string API_Key = "apikey";
string url = @"https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=" + API_Key;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
// json-formatted string from maps api
string responseFromServer = reader.ReadToEnd();
//richTextBox1.Text = responseFromServer;
}
}
json 回复:
"results" : [
{
"address_components" : [
{
"long_name" : "Somepostalcode",
"short_name" : "Somepostalcode",
"types" : [ "postal_code" ]
},
{
"long_name" : "Somelocality",
"short_name" : "Somelocality",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Someadministrative_area_level_2",
"short_name" : "Someadministrative_area_level_2",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "SOmeProvince",
"short_name" : "SomeShortname",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "SomeCountry",
"short_name" : "SomeCountryShortage",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "foratted adress",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : ,
"lng" :
},
"southwest" : {
"lat" : ,
"lng" :
}
},
"location" : {
"lat" : ,
"lng" :
},
"location_type" : "",
"viewport" : {
"northeast" : {
"lat" : ,
"lng" :
},
"southwest" : {
"lat" : ,
"lng" :
}
}
},
"place_id" : "",
"types" : [ "postal_code" ]
}
], "status" : "OK" }
正如@ZoharPeled 在评论中所说,我可以使用 JsonPath to query json using SelectToken As shown in Querying JSON with SelectToken
var jObject = JObject.Parse(json);
var userProfile = jObject.SelectToken("UserProfileResource.*.data.profile").ToObject<UserProfile>();
在示例中,我将我的 json 解析为 JObject
,然后使用 SelectToken
从中解析 select 配置文件数据。如您所见,我也在那里使用了 JSONPath 表达式。
*
表示
wildcard. All objects/elements regardless their names.