Home > OS >  How to "pass" a variable value to a JSON dynamic object?
How to "pass" a variable value to a JSON dynamic object?

Time:10-10

I dont know how to correctly say it, that´s why i wrote "pass" (please correct me). What i am trying to do is to retrieve a value from an JSON object depending on another variable value

This is the code

WebClient client = new WebClient();
string list = client.DownloadString("https://linkto.json");
dynamic json = JsonConvert.DeserializeObject(list);
var2 = json.variable[0].image;

It needs to read the variable value where it says "variable" but im not sure if this is possible or if it´s done in another way

Another edit: The "variable" on the code is where the variable should be read, i don't know either how to make it to read the value or anything

I tried searching on this forum and on the internet but im not sure what to search or what should i use

Thanks in advance for any answer!

Edit:

Here is the JSON string

{
  "Person1": [
    {
    "image": "http://linktoimage.com",
    "icon": "http://linktoicon.com",
    "background": ""
    }
  ],
  "Person2": [
    {
    "image": "https://linktoimage",
    "icon": "",
    "background": "no-background"
    }
  ]
}

A short example of the JSON string

Another edit: The JSON string can change over time, with new arrays

CodePudding user response:

The best way to use data is to deserialize your downloaded json

string json = client.DownloadString("https://linkto.json");
var jsonDeserialized= JsonSerializer.Deserialize<Dictionary<string, List<PersonImage>> >(json).ToList();
List<Person> persons = jsonDeserialized.Select(j => new Person { Name = j.Key, Images = j.Value }).ToList();

persons in jason format

[
  {
    "Name": "Person1",
    "Images": [
      {
        "image": "http://linktoimage.com",
        "icon": "http://linktoicon.com",
        "background": ""
      }
    ]
  },
  {
    "Name": "Person2",
    "Images": [
      {
        "image": "https://linktoimage",
        "icon": "",
        "background": "no-background"
      }
    ]
  }
]

test, the first image of person who has a name "Person1"

var image=persons.FirstOrDefault(p => p.Name=="Person1").Images[0].image; // http://linktoimage.com

classes

public class Person
{
    public string Name { get; set; }
    public List<PersonImage> Images {get;set;}
}
 public class PersonImage
{
    public string image { get; set; }
    public string icon { get; set; }
    public string background { get; set; }
}

CodePudding user response:

So i managed to do this by modifying the JSON format, i did it like this

{"Games":[
{
         "titleimage": "",
         "titleicon": "",
         "titlebackground": ""
},
{
         "titleimage": "",
         "titleicon": "",
         "titlebackground": ""
},
{
        "titleimage": "",
        "titleicon": "",
        "titlebackground": ""
}]
}

So then I can use Foreach to get to the value

  • Related