Xamarin C# выбор элементов в jsonArray - PullRequest
0 голосов
/ 07 апреля 2020

Я изучаю формы Xamarin и c#, я хотел бы выбрать 3 первых элемента в JsonArray 'real_examples' и добавить только значение ключей "src" adn "dst" в списке List<(string,string)> DescriptList

Вот 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"
        }

    ]

Вот мой код:

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>();

Спасибо за вашу помощь

1 Ответ

1 голос
/ 07 апреля 2020

Вставить Json как классы:

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; }
}

Для лучшей производительности я использую строку выстрела для замены в json данных.

    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'
    }
    ]
   }
 ";

Используйте linq для получения 2 JsonObjects значения "sr c" и "dst" в список.

 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();

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...