Home > Software design >  How to extract data from JSON array
How to extract data from JSON array

Time:02-24

I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:

String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("RecycleSiteUrl"));

I want to extract RecycleSiteUrl based on SiteId

My JSON data that I have goes like this :

 [
    {
    "SiteId": 1,
    "RecycleLogoUrl": "https://static-contrado.s3-eu-west- 1.amazonaws.com/cms/recyclecarelabel/d867c499-abc0-4ade-bc1a-f5011032c3e0132901511939451201.jpeg",
    "RecycleSiteUrl": "bagsoflove.co.uk/recycling",
    "Culture": "en-GB"
    },
    {
    "SiteId": 10,
    "RecycleLogoUrl": "https://static-contrado.s3-eu-west-1.amazonaws.com/cms/recyclecarelabel/95d28588-33e3-420c-8b24-4a8095c0f6ac132901511364264751.jpeg",
    "RecycleSiteUrl": "contrado.co.uk/recycling",
    "Culture": "en-GB"
    }]

I dont really have a strong grasp of this stuff so all the help is appreciated.

CodePudding user response:

using Newtonsoft.Json;  
using System.Linq;  

public void Method()
{
   var yourSearchParameter = 10;
   string jsonStr = readURL("//my URL is here");
   var obj = JsonConvert.DeserializeObject<List<RecycleSite>>(jsonStr);
   var siteUrl = obj.SingleOrDefault(q => q.SiteId == yourSearchParameter).RecycleSiteUrl;
 /* Do something with the siteUrl  */
}

public class RecycleSite
{
   public int SiteId { get; set; }
   public string RecycleLogoUrl { get; set; }
   public string RecycleSiteUrl { get; set; }
   public string Culture{ get; set; }
}

CodePudding user response:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

public Class Site
{
    public string GetRecycleSiteUrl(int siteId, string jsonArray)
    {
        var siteInfos = JsonConvert.DeserializeObject<List<SiteInfo>>(jsonArray);
        string recycleSiteUrl = siteInfos.FirstOrDefault(info => info.SiteId == siteId).RecycleSiteUrl;
        return recycleSiteUrl;
    }
}

public class SiteInfo
{
    public int SiteId { get; set; }
    public string RecycleLogoUrl { get; set; }
    public string RecycleSiteUrl { get; set; }
    public string Culture { get; set; }
}

You can create Site object and access GetRecycleSiteUrl method by passing respective parameter values.

  • Related