使用newtonsoft.json从httprequest获取几个属性



我需要从Google解析此类响应:

https://trends.google.com/trends/api/explore?hl= en-us&tz=-180& req =; req={"ComparisonItem":[{{"Keyt%22,%22GEO%22:%22%22,%22Time%22:%22-today 12-m%22%7d%5D,%22类别%22:0,%22Property%22:%22%22%22%22%7D&tz = -180

响应看起来像这样

other properties: ...
widgets: [{token: ""},...]

用于发送请求,我正在使用重新启动。Google的重新酶响应我想映射到我的模型

public class TokenResult
{
    [JsonProperty("widgets[0].token")]
    public string Token { get; set; }
}

当重新启动试图解析响应时,我会遇到错误。那么如何从第一个小部件中只有一个令牌?

讨论了问题的要求后,您可以使用dynamic从JSON字符串中获取token而无需使用模型类。工作演示在这里:https://dotnetfiddle.net/bgl8az

using System;
using Newtonsoft.Json;
public class Program
{
    public static void Main()
    {
        string json=@"{'widgets':[{'request':{'time':'2018-07-09 2019-07-09','resolution':'WEEK','locale':'en-US','comparisonItem':[{'geo':{},'complexKeywordsRestriction':{'keyword':[{'type':'BROAD','value':'react'}]}}],'requestOptions':{'property':'','backend':'IZG','category':0}},'lineAnnotationText':'Search interest','bullets':[{'text':'react'}],'showLegend':false,'showAverages':false,'helpDialog':{'title':'Interest over time','content':'Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. A score of 0 means there was not enough data for this term.'},'token':'APP6_UEAAAAAXSXKDwW-kwcTrkXhBuCj17xOewtWmROU','id':'TIMESERIES','type':'fe_line_chart','title':'Interest over time','template':'fe','embedTemplate':'fe_embed','version':'1','isLong':true,'isCurated':false},{'request':{'geo':{},'comparisonItem':[{'time':'2018-07-09 2019-07-09','complexKeywordsRestriction':{'keyword':[{'type':'BROAD','value':'react'}]}}],'resolution':'COUNTRY','locale':'en-US','requestOptions':{'property':'','backend':'IZG','category':0}},'geo':'world','resolution':'countries','searchInterestLabel':'Search interest','displayMode':'regions','helpDialog':{'title':'Interest by region','content':'See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular. A value of 0 indicates a location where there was not enough data for this term. u003cpu003eu003cpu003e u003cbu003eNote:u003c/bu003e A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for 'bananas' will get twice the score of a giant country where only 40% of the queries are for 'bananas'.','url':'https://support.google.com/trends/answer/4355212'},'color':'PALETTE_COLOR_1','index':0,'bullet':'react','token':'APP6_UEAAAAAXSXKD-rIwyhC21Abw8P2nPfb7AGhxrZ1','id':'GEO_MAP','type':'fe_geo_chart_explore','title':'Interest by region','template':'fe','embedTemplate':'fe_embed','version':'1','isLong':true,'isCurated':false},{'request':{'restriction':{'geo':{},'time':'2018-07-09 2019-07-09','originalTimeRangeForExploreUrl':'today 12-m','complexKeywordsRestriction':{'keyword':[{'type':'BROAD','value':'react'}]}},'keywordType':'ENTITY','metric':['TOP','RISING'],'trendinessSettings':{'compareTime':'2017-07-08 2018-07-08'},'requestOptions':{'property':'','backend':'IZG','category':0},'language':'en'},'helpDialog':{'title':'Related topics','content':'Users searching for your term also searched for these topics. You can view by the following metrics: u003cpu003e* u003cbu003eTopu003c/bu003e - The most popular topics. Scoring is on a relative scale where a value of 100 is the most commonly searched topic and a value of 50 is a topic searched half as often as the most popular term, and so on. u003cpu003e* u003cbu003eRisingu003c/bu003e - Related topics with the biggest increase in search frequency since the last time period. Results marked 'Breakout' had a tremendous increase, probably because these topics are new and had few (if any) prior searches.'},'color':'PALETTE_COLOR_1','keywordName':'react','token':'APP6_UEAAAAAXSXKD9wlRrdtpbUyYXxko216LXZt21ra','id':'RELATED_TOPICS','type':'fe_related_searches','title':'Related topics','template':'fe','embedTemplate':'fe_embed','version':'1','isLong':false,'isCurated':false},{'request':{'restriction':{'geo':{},'time':'2018-07-09 2019-07-09','originalTimeRangeForExploreUrl':'today 12-m','complexKeywordsRestriction':{'keyword':[{'type':'BROAD','value':'react'}]}},'keywordType':'QUERY','metric':['TOP','RISING'],'trendinessSettings':{'compareTime':'2017-07-08 2018-07-08'},'requestOptions':{'property':'','backend':'IZG','category':0},'language':'en'},'helpDialog':{'title':'Related queries','content':'Users searching for your term also searched for these queries. You can sort by the following metrics: u003cpu003e* u003cbu003eTopu003c/bu003e - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often as the most popular query, and so on. u003cpu003e* u003cbu003eRisingu003c/bu003e - Queries with the biggest increase in search frequency since the last time period. Results marked 'Breakout' had a tremendous increase, probably because these queries are new and had few (if any) prior searches.','url':'https://support.google.com/trends/answer/4355000'},'color':'PALETTE_COLOR_1','keywordName':'react','token':'APP6_UEAAAAAXSXKD10s1DrnqESw00VH8rfqAEq4ZjmA','id':'RELATED_QUERIES','type':'fe_related_searches','title':'Related queries','template':'fe','embedTemplate':'fe_embed','version':'1','isLong':false,'isCurated':false}],'keywords':[{'keyword':'react','name':'react','type':'Search term'}],'timeRanges':['Past 12 months'],'examples':[],'shareText':'Explore search interest for react by time, location and popularity on Google Trends','shouldShowMultiHeatMapMessage':false}";
        dynamic data = JsonConvert.DeserializeObject(json);
        foreach(var result in data.widgets)
        {    
            Console.WriteLine(result.token);
        }
    }
}

输出:

APP6_UEAAAAAXSXKDwW-kwcTrkXhBuCj17xOewtWmROU
APP6_UEAAAAAXSXKD-rIwyhC21Abw8P2nPfb7AGhxrZ1
APP6_UEAAAAAXSXKD9wlRrdtpbUyYXxko216LXZt21ra
APP6_UEAAAAAXSXKD10s1DrnqESw00VH8rfqAEq4ZjmA

您需要照顾文本文件中实际的JSON字符串之前的额外字符才能正确工作。

使用.SelectTokens(path)

的替代解决方案
var json = "{nt"widgets": [{nttt"request": {ntttt"time": "2018-07-10 2019-07-10",ntttt"resolution": "WEEK",ntttt"locale": "en-US",ntttt"comparisonItem": [{ntttttt"geo": {},ntttttt"complexKeywordsRestriction": {nttttttt"keyword": [{nttttttttt"type": "BROAD",nttttttttt"value": "react"ntttttttt}nttttttt]ntttttt}nttttt}ntttt],ntttt"requestOptions": {nttttt"property": "",nttttt"backend": "IZG",nttttt"category": 0ntttt}nttt},nttt"lineAnnotationText": "Search interest",nttt"bullets": [{nttttt"text": "react"ntttt}nttt],nttt"showLegend": false,nttt"showAverages": false,nttt"helpDialog": {ntttt"title": "Interest over time",ntttt"content": "Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. A score of 0 means there was not enough data for this term."nttt},nttt"token": "APP6_UEAAAAAXSbu2jqA25pSUFsKBYxQA0kFsKdcLCgU",nttt"id": "TIMESERIES",nttt"type": "fe_line_chart",nttt"title": "Interest over time",nttt"template": "fe",nttt"embedTemplate": "fe_embed",nttt"version": "1",nttt"isLong": true,nttt"isCurated": falsentt}, {nttt"request": {ntttt"geo": {},ntttt"comparisonItem": [{ntttttt"time": "2018-07-10 2019-07-10",ntttttt"complexKeywordsRestriction": {nttttttt"keyword": [{nttttttttt"type": "BROAD",nttttttttt"value": "react"ntttttttt}nttttttt]ntttttt}nttttt}ntttt],ntttt"resolution": "COUNTRY",ntttt"locale": "en-US",ntttt"requestOptions": {nttttt"property": "",nttttt"backend": "IZG",nttttt"category": 0ntttt}nttt},nttt"geo": "world",nttt"resolution": "countries",nttt"searchInterestLabel": "Search interest",nttt"displayMode": "regions",nttt"helpDialog": {ntttt"title": "Interest by region",ntttt"content": "See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular. A value of 0 indicates a location where there was not enough data for this term. \u003cp\u003e\u003cp\u003e \u003cb\u003eNote:\u003c/b\u003e A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for \"bananas\" will get twice the score of a giant country where only 40% of the queries are for \"bananas\".",ntttt"url": "https://support.google.com/trends/answer/4355212"nttt},nttt"color": "PALETTE_COLOR_1",nttt"index": 0,nttt"bullet": "react",nttt"token": "APP6_UEAAAAAXSbu2q_7M5NSV_6S_n66X17hnN3geL_X",nttt"id": "GEO_MAP",nttt"type": "fe_geo_chart_explore",nttt"title": "Interest by region",nttt"template": "fe",nttt"embedTemplate": "fe_embed",nttt"version": "1",nttt"isLong": true,nttt"isCurated": falsentt}, {nttt"request": {ntttt"restriction": {nttttt"geo": {},nttttt"time": "2018-07-10 2019-07-10",nttttt"originalTimeRangeForExploreUrl": "today 12-m",nttttt"complexKeywordsRestriction": {ntttttt"keyword": [{ntttttttt"type": "BROAD",ntttttttt"value": "react"nttttttt}ntttttt]nttttt}ntttt},ntttt"keywordType": "ENTITY",ntttt"metric": ["TOP", "RISING"],ntttt"trendinessSettings": {nttttt"compareTime": "2017-07-09 2018-07-09"ntttt},ntttt"requestOptions": {nttttt"property": "",nttttt"backend": "IZG",nttttt"category": 0ntttt},ntttt"language": "en"nttt},nttt"helpDialog": {ntttt"title": "Related topics",ntttt"content": "Users searching for your term also searched for these topics. You can view by the following metrics: \u003cp\u003e* \u003cb\u003eTop\u003c/b\u003e - The most popular topics. Scoring is on a relative scale where a value of 100 is the most commonly searched topic and a value of 50 is a topic searched half as often as the most popular term, and so on. \u003cp\u003e* \u003cb\u003eRising\u003c/b\u003e - Related topics with the biggest increase in search frequency since the last time period. Results marked \"Breakout\" had a tremendous increase, probably because these topics are new and had few (if any) prior searches."nttt},nttt"color": "PALETTE_COLOR_1",nttt"keywordName": "react",nttt"token": "APP6_UEAAAAAXSbu2j6t0UwOOyihkflYRxWkIyxgSgNY",nttt"id": "RELATED_TOPICS",nttt"type": "fe_related_searches",nttt"title": "Related topics",nttt"template": "fe",nttt"embedTemplate": "fe_embed",nttt"version": "1",nttt"isLong": false,nttt"isCurated": falsentt}, {nttt"request": {ntttt"restriction": {nttttt"geo": {},nttttt"time": "2018-07-10 2019-07-10",nttttt"originalTimeRangeForExploreUrl": "today 12-m",nttttt"complexKeywordsRestriction": {ntttttt"keyword": [{ntttttttt"type": "BROAD",ntttttttt"value": "react"nttttttt}ntttttt]nttttt}ntttt},ntttt"keywordType": "QUERY",ntttt"metric": ["TOP", "RISING"],ntttt"trendinessSettings": {nttttt"compareTime": "2017-07-09 2018-07-09"ntttt},ntttt"requestOptions": {nttttt"property": "",nttttt"backend": "IZG",nttttt"category": 0ntttt},ntttt"language": "en"nttt},nttt"helpDialog": {ntttt"title": "Related queries",ntttt"content": "Users searching for your term also searched for these queries. You can sort by the following metrics: \u003cp\u003e* \u003cb\u003eTop\u003c/b\u003e - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often as the most popular query, and so on. \u003cp\u003e* \u003cb\u003eRising\u003c/b\u003e - Queries with the biggest increase in search frequency since the last time period. Results marked \"Breakout\" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.",ntttt"url": "https://support.google.com/trends/answer/4355000"nttt},nttt"color": "PALETTE_COLOR_1",nttt"keywordName": "react",nttt"token": "APP6_UEAAAAAXSbu2mSFz-N3e9aT0TUMZbJ-YOtU2Qjp",nttt"id": "RELATED_QUERIES",nttt"type": "fe_related_searches",nttt"title": "Related queries",nttt"template": "fe",nttt"embedTemplate": "fe_embed",nttt"version": "1",nttt"isLong": false,nttt"isCurated": falsentt}nt],nt"keywords": [{nttt"keyword": "react",nttt"name": "react",nttt"type": "Search term"ntt}nt],nt"timeRanges": ["Past 12 months"],nt"examples": [],nt"shareText": "Explore search interest for react by time, location and popularity on Google Trends",nt"shouldShowMultiHeatMapMessage": falsen}n";
var obj = JToken.Parse(json);
var tokens = obj.SelectTokens("widgets[*].token");

最新更新