Reputation: 147
I am Learning Xamarin Forms and c#, I would like to Select the 3 first elements in The JsonArray 'real_examples" and only add the value of the keys "src" adn "dst"
in the list List<(string,string)> DescriptList
Here is the Json:
"real_examples": [
{
"id": "",
"src": "Atualmente, o couro não vem apenas de vacas ou porcos; também é feito de avestruz [...] ou até mesmo de bacalhau.",
"dst": "These days, leather doesn't just come from cows or pigs; it's also made [...] from ostriches or even cod.",
"url": "http://webmagazine.lanxess.com.br/de/pagina-inicial/couro/um-material-antigo/druck/print-page.html"
},
{
"id": "",
"src": "As práticas de pesca actuais representam uma ameaça séria [...] para a conservação e a reconstituição das [...] unidades populacionais de bacalhau no mar Báltico e exigem [...] uma acção imediata.",
"dst": "Current fishing practice constitutes a [...] serious threat to the conservation and [...] the rebuilding of the cod stocks in the Baltic [...] Sea and requires immediate action.",
"url": "http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ:L:2003:097:0031:0031:PT:PDF"
},
{
"id": "",
"src": "Porém, dadas as diferenças biológicas [...] entre estas espécies, uma determinada [...] malhagem reterá o bacalhau melhor do que a arinca [...] e ainda melhor do que o badejo.",
"dst": "But, because of biological differences among these species, one net [...] mesh size will retain cod better than haddock [...] and certainly better than whiting.",
"url": "http://ec.europa.eu/fisheries/cfp/management_resources/conservation_measures/technical_measures_pt.htm"
},
{
"id": "",
"src": "É calculado o esforço de [...] pesca de todos os navios que capturam bacalhau.",
"dst": "The fishing effort of all [...] the vessels catching cod will be calculated.",
"url": "http://europa.eu/rapid/pressReleasesAction.do?reference=IP/03/631\u0026format=HTML\u0026aged=1\u0026language=PT\u0026guiLanguage=en"
},
{
"id": "",
"src": "Na sequência de consultas com base no presente documento e da recepção dos últimos pareceres científicos, a Comissão pretende apresentar, no [...] final do ano, propostas de regulamentos do Conselho relativas a planos de recuperação [...] completos para o bacalhau e a pescada.",
"dst": "Following consultations on the basis of this document and the receipt of the latest scientific advice, the Commission intends to [...] present towards the end of this year proposals for Council Regulations dealing with [...] full recovery plans for cod and hake.",
"url": "http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=COM:2001:0326:FIN:PT:PDF"
}
]
Here is my code :
string urlParameters = "?q=" + word + "&src=" + source_langue + "&dst=" + dest_langue + "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
JObject joResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
JArray MyJsonDescriptList = (JArray)joResponse["real_examples"];
// add the first 2 JsonObjects values of "src" adn "dst" in this list
List<(string,string)> DescriptList = new List<MyWordDescript>();
Thanks for your help
Upvotes: 0
Views: 118
Reputation: 10978
Paste Json as Classes:
public class MyWordDescript
{
public Real_Examples[] real_examples { get; set; }
}
public class Real_Examples
{
public string id { get; set; }
public string src { get; set; }
public string dst { get; set; }
public string url { get; set; }
}
For better performance, I use shot string to replace in json data.
var json = @"{
'real_examples': [
{
'id': '',
'src': 'src1',
'dst': 'dst1',
'url': 'url1'
},
{
'id': '',
'src': 'src2',
'dst': 'dst2',
'url': 'url2'
},
{
'id': '',
'src': 'src3',
'dst': 'dsy3',
'url': 'url3'
},
{
'id': '',
'src': 'src4',
'dst': 'dst4',
'url': 'url4'
},
{
'id': '',
'src': 'src5',
'dst': 'dst5',
'url': 'url5'
}
]
}
";
Use linq to get the 2 JsonObjects values of "src" adn "dst" into list.
JObject joResponse = JObject.Parse(json);
JArray MyJsonDescriptList = (JArray)joResponse["real_examples"];
// add the first 2 JsonObjects values of "src" adn "dst" in this list
var DescriptList = MyJsonDescriptList.GroupBy(b => new[] { b["src"], b["dst"] }).SelectMany(s => new[] {s.Key}).ToList();
Upvotes: 1