❔ How to get specific fields from a Http GET request

I am working with a test API for learning purposes, I am using the following snippet to actually return the request body:
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.Log(body);
}
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.Log(body);
}
I get a response such as:
{"results":[{"code":"1002227_group_013","name":"Cargo Joggers","stock":{"stockLevel":1},"price":{"currencyIso":"USD","value":39.99,"priceType":"BUY","formattedValue":"$ 39.99","type":"WHITE"},"images":[{"url":"https://lp2.hm.com/hmgoepprod?set=source[/66/07/660740532368338c273791d92e308e445a5af9c5.jpg],origin[dam],category[],type[DESCRIPTIVESTILLLIFE],res[m],hmver[2]&call=url[file:/product/style]","baseUrl":"https://image.hm.com/assets/hm/66/07/660740532368338c273791d92e308e445a5af9c5.jpg"}],"categories":[],"pk":"9461964111873","sellingAttributes":["New Arrival"],"whitePrice":{"currencyIso":"USD","value":39.99,"priceType":"BUY","formattedValue":"$ 39.99","type":"WHITE"},"articles":[{"code":"1002227013","name":"Cargo
{"results":[{"code":"1002227_group_013","name":"Cargo Joggers","stock":{"stockLevel":1},"price":{"currencyIso":"USD","value":39.99,"priceType":"BUY","formattedValue":"$ 39.99","type":"WHITE"},"images":[{"url":"https://lp2.hm.com/hmgoepprod?set=source[/66/07/660740532368338c273791d92e308e445a5af9c5.jpg],origin[dam],category[],type[DESCRIPTIVESTILLLIFE],res[m],hmver[2]&call=url[file:/product/style]","baseUrl":"https://image.hm.com/assets/hm/66/07/660740532368338c273791d92e308e445a5af9c5.jpg"}],"categories":[],"pk":"9461964111873","sellingAttributes":["New Arrival"],"whitePrice":{"currencyIso":"USD","value":39.99,"priceType":"BUY","formattedValue":"$ 39.99","type":"WHITE"},"articles":[{"code":"1002227013","name":"Cargo
How could I go about getting a specific field from this output, such as the "name" or "images"?
111 Replies
Axiss
Axiss2y ago
Typically you would deserialize that into an object that you control. Create a class that has properties that have the same names as the fields in the JSON and use either NewtonSoft or System.Text.Json to deserialze that into a class. Another option is using something like JsonPath to query the fields that you need. https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm
dankmememachine
dankmememachineOP2y ago
So if I just wanted an object that held the image and name would that be possible?
Angius
Angius2y ago
await client.GetAsJsonAsync<Model>(url)
Axiss
Axiss2y ago
Yep. You don't need to create a property for each field. Just the ones you need.
dankmememachine
dankmememachineOP2y ago
so this is the changes:
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
ClothingAttributes clothingAttributes = new ClothingAttributes();
Debug.Log(body);
}
}
}

public class ClothingAttributes{
string name;
string image;
}
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
ClothingAttributes clothingAttributes = new ClothingAttributes();
Debug.Log(body);
}
}
}

public class ClothingAttributes{
string name;
string image;
}
obviously no connection yet, you mentioned JSON etc, is there a best method to deserialize? sorry if that doesn't make a lot of sense, i'm new to working with requests
Axiss
Axiss2y ago
Look at what ZZZZZZZZ posted
dankmememachine
dankmememachineOP2y ago
where would that fit into this code? and what should go into <Model> and (url)? the URL currently being used in the request is
https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers
https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers
Angius
Angius2y ago
Model is the class you want to deserialize to url is the... url
Axiss
Axiss2y ago
I'd need to see a bit more, but instead of var response = await client.SendAsync(request) it's var response = await client.GetAsJsonAsync<ClothingAttributes>(your url here);
Angius
Angius2y ago
Assuming client is an HttpClient of course
dankmememachine
dankmememachineOP2y ago
I can post the whole script, this is in a Unity project:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;


public class API_Test : MonoBehaviour
{
/*ladies_all
* //ladies_trousers // ladies_jeans
* //ladies_jacketscoats_coats
//ladies_premium_selection_tops
*/

/*Categories:
* men_all
* //pants: men_trousers
* //jacket: men_blazerssuits
* //shirt: men_shirts */
public string theGender;
private async void Start() => await StartAsync(theGender);


private async void GenerateOutfit()
{
if(theGender == "ladies")
{
await StartAsync("");
} else
{

}
}
async Task StartAsync(string gender)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
ClothingAttributes clothingAttributes = new ClothingAttributes();
Debug.Log(body);
}
}
}

public class ClothingAttributes{
string name;
string image;
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;


public class API_Test : MonoBehaviour
{
/*ladies_all
* //ladies_trousers // ladies_jeans
* //ladies_jacketscoats_coats
//ladies_premium_selection_tops
*/

/*Categories:
* men_all
* //pants: men_trousers
* //jacket: men_blazerssuits
* //shirt: men_shirts */
public string theGender;
private async void Start() => await StartAsync(theGender);


private async void GenerateOutfit()
{
if(theGender == "ladies")
{
await StartAsync("");
} else
{

}
}
async Task StartAsync(string gender)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
ClothingAttributes clothingAttributes = new ClothingAttributes();
Debug.Log(body);
}
}
}

public class ClothingAttributes{
string name;
string image;
}
Angius
Angius2y ago
Ah oof ouch my bones Unity First of all, async void is the devil Second, you have an API key in this code
dankmememachine
dankmememachineOP2y ago
In the end i want to be able to click a button for male or female and put an outfit on screen generated from this H&M API Right, this is a free test website for messing with different APIs, this is a local hobby project for learning so is it bad to provide it here?
Angius
Angius2y ago
Someone can now make requests to this API on your behalf Usually not the best thing to have happen
dankmememachine
dankmememachineOP2y ago
right, well i can generate a new one after this then, like i said i'm just using this for personal learning
Angius
Angius2y ago
Regardless, it seems you are using HttpClient so my code should work Although... I think this extension method uses System.Text.Json Which Unity doesn't support So you might need to go oldschool after all
Axiss
Axiss2y ago
You'll need a lot more classes to get what you want, it's nested response.
Angius
Angius2y ago
$jsongen
MODiX
MODiX2y ago
Use https://app.quicktype.io or https://json2csharp.com to generate classes from your JSON
Instantly parse JSON in any language | quicktype
Whether you're using C#, Swift, TypeScript, Go, C++ or other languages, quicktype generates models and helper code for quickly and safely reading JSON in your apps. Customize online with advanced options, or download a command-line tool.
Convert JSON to C# Classes Online - Json2CSharp Toolkit
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
dankmememachine
dankmememachineOP2y ago
Yeah haha I don't know what most of this means, why can't I use this class I made and just create new ones for each clothing item?
Angius
Angius2y ago
The class has to match the JSON Period
dankmememachine
dankmememachineOP2y ago
in the end i need 3 requests for 3 item types, and then need an image and their name
Angius
Angius2y ago
It can skip some properties, but the properties it has have to match Period
dankmememachine
dankmememachineOP2y ago
ok, so then for this object :
public class ClothingAttributes{
string name;
string image;
}
public class ClothingAttributes{
string name;
string image;
}
are these names not correctly formatted?
Axiss
Axiss2y ago
For your json, I cleaned it up a bit and generated this: public class Image { public string url { get; set; } public string baseUrl { get; set; } } public class Price { public string currencyIso { get; set; } public double value { get; set; } public string priceType { get; set; } public string formattedValue { get; set; } public string type { get; set; } } public class Result { public string code { get; set; } public string name { get; set; } public Stock stock { get; set; } public Price price { get; set; } public List<Image> images { get; set; } public List<object> categories { get; set; } public string pk { get; set; } public List<string> sellingAttributes { get; set; } public WhitePrice whitePrice { get; set; } } public class Root { public List<Result> results { get; set; } }
dankmememachine
dankmememachineOP2y ago
ok, and these append to my current code? as new objects for each of these fields in the .cs file?
Angius
Angius2y ago
If the JSON is
{
"images": [
{
"url": "..."
}
]
}
{
"images": [
{
"url": "..."
}
]
}
you can't deserialize it to
public class ClothingAttributes
{
public string Name { get; set; }
public string image { get; set; }
}
public class ClothingAttributes
{
public string Name { get; set; }
public string image { get; set; }
}
You place those wherever You send a Get request to the API and get a JSON string back Then you use (ugh) Newtonsoft.Json to deserialize that JSON to the Root class
dankmememachine
dankmememachineOP2y ago
ok, so the object has to match exactly to the fields of the JSON, so each section of the JSON I want to use needs to be treated like an object? so in the example above:
public class Image
{
public string url { get; set; }
public string baseUrl { get; set; }
}
public class Image
{
public string url { get; set; }
public string baseUrl { get; set; }
}
Angius
Angius2y ago
Objects need to be treated as objects, lists as lists
dankmememachine
dankmememachineOP2y ago
this would satisfy the JSON conversion to extract the image results?
Angius
Angius2y ago
But yes
Axiss
Axiss2y ago
Yes, but you'll get a list of images
dankmememachine
dankmememachineOP2y ago
ok, and some of the lines it complains about:
dankmememachine
dankmememachineOP2y ago
do these need their own classes defined as well?
Axiss
Axiss2y ago
Yes, unless you don't need them
dankmememachine
dankmememachineOP2y ago
Or can they be removed if i dont need them ok got it so how can I extract into these classes from the response? If I wanted to get like, pants and a shirt, and get the name and image for each I added in newstonsoft
Angius
Angius2y ago
var json = await client.GetStringAsync(url);
var data = JsonConverter.Deserialize<YourCoolClass>(json);
var json = await client.GetStringAsync(url);
var data = JsonConverter.Deserialize<YourCoolClass>(json);
Then the data will be an instance of YourCoolClass
dankmememachine
dankmememachineOP2y ago
ok, so would coolclass be the root in this instance?
Angius
Angius2y ago
Yep Also, since you're using async void it'll swallow exceptions. Not sure how Unity handles asynchronous button clicks and stuff, though So wrap the whole thing in a try catch, log the exception, and later on look into how it should be done properly
dankmememachine
dankmememachineOP2y ago
it says JsonConverter has no Deserialize def
Angius
Angius2y ago
Idk, maybe Convert or something? Haven't used Newtonsoft in years See what IntelliSense tells you
dankmememachine
dankmememachineOP2y ago
dankmememachine
dankmememachineOP2y ago
but it isn't auto suggesting here:
Axiss
Axiss2y ago
Try JsonConvert
dankmememachine
dankmememachineOP2y ago
yeah that one works so this root class isn't static, do I need to create an object of it to get fields? And what about the other classes and filling their data?
Axiss
Axiss2y ago
Nope. the Deserialize method will create the object and return it populated it's smart enough to instantiate all the types that it needs
dankmememachine
dankmememachineOP2y ago
ok, would i be able to debug.log the data object itself? or I guess, what can I do with this data var now? using the new snippet
var json = await client.GetStringAsync("https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers");
var data = JsonConvert.DeserializeObject<Root>(json);
Debug.Log(data);
var json = await client.GetStringAsync("https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers");
var data = JsonConvert.DeserializeObject<Root>(json);
Debug.Log(data);
returns a 401 error
Axiss
Axiss2y ago
Use your original code to get the response using (var response = await client.SendAsync(request)) { response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync(); // Deserialize code var data = JsonConvert.DeserializeObject<Root>(body); Debug.Log(body); } We got a little wrapped around how you were sending and getting the data before we knew it was unity and there was an api key involved
dankmememachine
dankmememachineOP2y ago
so where would
var data = JsonConvert.DeserializeObject<Root>(json);
var data = JsonConvert.DeserializeObject<Root>(json);
fit into this? just replacing it with var data = JsonConvert.DeserializeObject<Root>(json); ? I created two objects:
public Root root = new Root();
public Result result = new Result();
public Root root = new Root();
public Result result = new Result();
the deserialize snippet returns the body in the debug but the objects are remaining empty in inspector snippet:
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
// Deserialize code
root = JsonConvert.DeserializeObject<Root>(body);
Debug.Log(body);
}
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
// Deserialize code
root = JsonConvert.DeserializeObject<Root>(body);
Debug.Log(body);
}
to be clear, current file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;
using Newtonsoft.Json;


public class API_Test : MonoBehaviour
{
public string theGender;
private async void Start() => await StartAsync(theGender);

public Root root = new Root();
public Result result = new Result();

async Task StartAsync(string gender)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
// Deserialize code
root = JsonConvert.DeserializeObject<Root>(body);
Debug.Log(body);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;
using Newtonsoft.Json;


public class API_Test : MonoBehaviour
{
public string theGender;
private async void Start() => await StartAsync(theGender);

public Root root = new Root();
public Result result = new Result();

async Task StartAsync(string gender)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
// Deserialize code
root = JsonConvert.DeserializeObject<Root>(body);
Debug.Log(body);
}
}
}
(not including the classes below it) I also tried
root = JsonUtility.FromJson<Root>(body);
result = JsonUtility.FromJson<Result>(body);
root = JsonUtility.FromJson<Root>(body);
result = JsonUtility.FromJson<Result>(body);
but the body debug always returns the info and the root/result objects are still blank in the inspector
Angius
Angius2y ago
Why do you create those instances? No need to
dankmememachine
dankmememachineOP2y ago
I'm just trying to still figure out how to get this data into a manipulatable state
Angius
Angius2y ago
JsonConvert.DeserializeObject<Root>(body) will return an instance of Root
dankmememachine
dankmememachineOP2y ago
would
root = JsonUtility.FromJson<Root>(body);
root = JsonUtility.FromJson<Root>(body);
do the same? I realized JsonUtility was added to Unity
Angius
Angius2y ago
Idk, maybe?
dankmememachine
dankmememachineOP2y ago
ok, so i have an instance of root, I can't see it anywhere though, how would I go from this deserialized root to getting the name of the item
Angius
Angius2y ago
root that instance And you would use... the properties of it If it has an Images property, well, access it root.Images If Images is a list, well, treat it as a list and loop over it, or get nth element
dankmememachine
dankmememachineOP2y ago
i see this:
Axiss
Axiss2y ago
I threw your code into a Console app, and I'm getting data back
Axiss
Axiss2y ago
Axiss
Axiss2y ago
Yeah, Root doesn't have that it has a List<Result>
Angius
Angius2y ago
Look at the class you have It'll give you all the information you need
dankmememachine
dankmememachineOP2y ago
ok @Axiss do I need to create an Image object?
Axiss
Axiss2y ago
no You need to navigate the deserialized object root.results is a list each result has the properties you are looking for
dankmememachine
dankmememachineOP2y ago
ok, let me try that
dankmememachine
dankmememachineOP2y ago
if I debug log the root.list I get:
dankmememachine
dankmememachineOP2y ago
*root.results
Axiss
Axiss2y ago
Yeah, that's expected you handed Debug.Log a List<Result> and it wrote out it's name What are you trying to do with these results?
dankmememachine
dankmememachineOP2y ago
I just need the name of the item and the photo of it
Angius
Angius2y ago
Access and log those, then
dankmememachine
dankmememachineOP2y ago
I'm not understanding how to do that, i have serializable classes for Image and Result but do not know how to fill them
Angius
Angius2y ago
You don't fill them You don't even instantiate those classes manually The deserialization does that for you
dankmememachine
dankmememachineOP2y ago
Ok, so with
public class Image
{
public string url { get; set; }
public string baseUrl { get; set; }
}
public class Image
{
public string url { get; set; }
public string baseUrl { get; set; }
}
How would I debug.log the image url after deserializing root?
Angius
Angius2y ago
From... root See what properties it has And traverse them until you get to the images
dankmememachine
dankmememachineOP2y ago
looking through here?
Angius
Angius2y ago
Here, and looking at the class results is a list in this case So... treat it as a list
dankmememachine
dankmememachineOP2y ago
like
Debug.Log(root.results.ToArray());
Debug.Log(root.results.ToArray());
?
Angius
Angius2y ago
It is an array/list What can you do with a list? You can loop over it for example
Axiss
Axiss2y ago
Your api call returned 30 results
dankmememachine
dankmememachineOP2y ago
right, but its giving me what looks like garbage in the debug log:
0x00007ff68e2769cd (Unity) StackWalker::GetCurrentCallstack
0x00007ff68e27d589 (Unity) StackWalker::ShowCallstack
0x00007ff68f200943 (Unity) GetStacktrace
0x00007ff68f8a091d (Unity) DebugStringToFile
0x00007ff68d33c262 (Unity) DebugLogHandler_CUSTOM_Internal_Log
0x000001b90257f72a (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,UnityEngine.LogOption,string,UnityEngine.Object)
0x000001b90257f5bb (Mono JIT Code) UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
0x000001b90257eade (Mono JIT Code) UnityEngine.Logger:Log (UnityEngine.LogType,object)
0x000001b90257e77d (Mono JIT Code) UnityEngine.Debug:Log (object)
0x000001b927b6ba13 (Mono JIT Code) [API_Test.cs:47] API_Test/<StartAsync>d__2:MoveNext ()
0x00007ff68e2769cd (Unity) StackWalker::GetCurrentCallstack
0x00007ff68e27d589 (Unity) StackWalker::ShowCallstack
0x00007ff68f200943 (Unity) GetStacktrace
0x00007ff68f8a091d (Unity) DebugStringToFile
0x00007ff68d33c262 (Unity) DebugLogHandler_CUSTOM_Internal_Log
0x000001b90257f72a (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,UnityEngine.LogOption,string,UnityEngine.Object)
0x000001b90257f5bb (Mono JIT Code) UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
0x000001b90257eade (Mono JIT Code) UnityEngine.Logger:Log (UnityEngine.LogType,object)
0x000001b90257e77d (Mono JIT Code) UnityEngine.Debug:Log (object)
0x000001b927b6ba13 (Mono JIT Code) [API_Test.cs:47] API_Test/<StartAsync>d__2:MoveNext ()
```
Angius
Angius2y ago
That's why you loop over it... Loop Loop Loop Loop
Axiss
Axiss2y ago
there isn't A image and A name
Angius
Angius2y ago
An array or a list will never be converted to a string properly
dankmememachine
dankmememachineOP2y ago
@Axiss yes, that is what it does in the tests online, 30 results for any of the tags i enter in this case "men_trousers"
Angius
Angius2y ago
Not will a random class
dankmememachine
dankmememachineOP2y ago
ok, sorry again I am new to this, so how would i go about looping over this?
Angius
Angius2y ago
You need to go over the results, and get the data of each object, as needed With... a loop foreach (var whatever in root.results)
dankmememachine
dankmememachineOP2y ago
ok, one sec, I know the syntax for a loop i didnt know what to put in would something like this be on the right track?
foreach(var item in root.results)
{
Debug.Log(item);
}
foreach(var item in root.results)
{
Debug.Log(item);
}
Angius
Angius2y ago
item is a class So you'll also get garbage output to the console Try one of the properties of item
dankmememachine
dankmememachineOP2y ago
ohhhh one sec im using
foreach(var item in root.results)
{
Debug.Log(item.name);
}
foreach(var item in root.results)
{
Debug.Log(item.name);
}
, also used item.images and am getting garbage, so I need to set this 'item' as a list?
dankmememachine
dankmememachineOP2y ago
like, item.name is returning what seems to be what I want:
Axiss
Axiss2y ago
images is a list so you need to loop through it to read it
dankmememachine
dankmememachineOP2y ago
so like:
foreach(var item in root.results)
{
foreach(var image in item.images)
{
Debug.Log(image);
}
// Debug.Log(item.images);
}
foreach(var item in root.results)
{
foreach(var image in item.images)
{
Debug.Log(image);
}
// Debug.Log(item.images);
}
Axiss
Axiss2y ago
not quite image is an object, with properties public class Image { public string url { get; set; } public string baseUrl { get; set; } } you'll need to access image.url or image.baseUrl
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
using System.Text.Json;

class Foo
{
public string Name { get; set; }
public int[] Numbers { get; set; }
}
class Bar
{
public string Ungabunga { get; set; }
public Foo[] Foos { get; set; }
}

var json = """
{
"Ungabunga": "hello world",
"Foos": [
{
"Name": "Bob Bobbit",
"Numbers": [ 1, 2, 3, 4, 5 ]
},
{
"Name": "Mark Marksson",
"Numbers": [ 6, 7, 8, 9, 10 ]
}
]
}
""";

var data = JsonSerializer.Deserialize<Bar>(json);

Console.WriteLine($"The text is [{data.Ungabunga}]");
Console.WriteLine($"It contains [{data.Foos.Length}] foos:");
foreach (var foo in data.Foos)
{
Console.WriteLine($" This one is by [{foo.Name}]");
Console.WriteLine($" And has [{foo.Numbers.Length}] values:");
foreach (var num in foo.Numbers)
{
Console.WriteLine($" {num}");
}
}
using System.Text.Json;

class Foo
{
public string Name { get; set; }
public int[] Numbers { get; set; }
}
class Bar
{
public string Ungabunga { get; set; }
public Foo[] Foos { get; set; }
}

var json = """
{
"Ungabunga": "hello world",
"Foos": [
{
"Name": "Bob Bobbit",
"Numbers": [ 1, 2, 3, 4, 5 ]
},
{
"Name": "Mark Marksson",
"Numbers": [ 6, 7, 8, 9, 10 ]
}
]
}
""";

var data = JsonSerializer.Deserialize<Bar>(json);

Console.WriteLine($"The text is [{data.Ungabunga}]");
Console.WriteLine($"It contains [{data.Foos.Length}] foos:");
foreach (var foo in data.Foos)
{
Console.WriteLine($" This one is by [{foo.Name}]");
Console.WriteLine($" And has [{foo.Numbers.Length}] values:");
foreach (var num in foo.Numbers)
{
Console.WriteLine($" {num}");
}
}
Console Output
The text is [hello world]
It contains [2] foos:
This one is by [Bob Bobbit]
And has [5] values:
1
2
3
4
5
This one is by [Mark Marksson]
And has [5] values:
6
7
8
9
10
The text is [hello world]
It contains [2] foos:
This one is by [Bob Bobbit]
And has [5] values:
1
2
3
4
5
This one is by [Mark Marksson]
And has [5] values:
6
7
8
9
10
Compile: 743.247ms | Execution: 125.938ms | React with ❌ to remove this embed.
dankmememachine
dankmememachineOP2y ago
I don't seem to be able to just append it with .url:
Angius
Angius2y ago
The image will have the url item.images is a list of images Again, look at the classes you have
dankmememachine
dankmememachineOP2y ago
ok, i see that now sorry, would these terms be considered accessors? How would I be able to read up on knowing how to access stuff like this in the future? the snippet above is helpful as well so what I have now is
foreach(var item in root.results)
{
foreach(var image in item.images)
{
Debug.Log(image.url);
}

}
foreach(var item in root.results)
{
foreach(var image in item.images)
{
Debug.Log(image.url);
}

}
which works
Axiss
Axiss2y ago
Properties are what they are called in the C# world
Angius
Angius2y ago
Properties do stem from accessor methods, so I guess you could Java-ify the concept to that $getsetdevolve
MODiX
MODiX2y ago
class Foo
{
private int _bar;

public int GetBar()
{
return _bar;
}

public void SetBar(int bar)
{
_bar = bar;
}
}
class Foo
{
private int _bar;

public int GetBar()
{
return _bar;
}

public void SetBar(int bar)
{
_bar = bar;
}
}
can be shortened to
class Foo
{
private int _bar;

public int GetBar() => _bar;

public void SetBar(int bar) => _bar = bar;
}
class Foo
{
private int _bar;

public int GetBar() => _bar;

public void SetBar(int bar) => _bar = bar;
}
can be shortened to
class Foo
{
private int _bar;
public int Bar {
get { return _bar; }
set { _bar = value; }
}
}
class Foo
{
private int _bar;
public int Bar {
get { return _bar; }
set { _bar = value; }
}
}
can be shortened to
class Foo
{
private int _bar;
public int Bar {
get => _bar;
set => _bar = value;
}
}
class Foo
{
private int _bar;
public int Bar {
get => _bar;
set => _bar = value;
}
}
can be shortened to
class Foo
{
public int Bar { get; set; }
}
class Foo
{
public int Bar { get; set; }
}
dankmememachine
dankmememachineOP2y ago
ok now that i understand how to access these properties I think I have almost everything I need i want to randomize a choice from 1 to 30 for the three seperate calls i will be making for the three seperate item types I can randomize something like:
Debug.Log(root.results[1].name);
Debug.Log(root.results[1].images[0]);
Debug.Log(root.results[1].name);
Debug.Log(root.results[1].images[0]);
to choose I guess my only other question is, should I simply call this
async Task StartAsync(string gender)
async Task StartAsync(string gender)
three times if I need say a shirt, a coat, and pants? the string there needs to be changed to the accessor for the categories such as
* //pants: men_trousers
* //jacket: men_blazerssuits
* //shirt: men_shirts */
* //pants: men_trousers
* //jacket: men_blazerssuits
* //shirt: men_shirts */
Angius
Angius2y ago
Depends on the API Can you get all of those things in a single call? Do You can't? Well, not much can be done besides calling the API multiple times
dankmememachine
dankmememachineOP2y ago
That I am unsure of, is there a way to test it? The api seems pretty barebones: https://rapidapi.com/apidojo/api/hm-hennes-mauritz/
RapidAPI
HM - Hennes Mauritz API Documentation (apidojo) | RapidAPI
H&M API helps to query for all information about regions, categories, products, etc... as on official websites
dankmememachine
dankmememachineOP2y ago
I just want to try to use good programming practices and minimize calls if I can, if not that is fine Right now I have it set up barebones like:
private async void Start() => await StartAsync("men_trousers");

async Task StartAsync(string itemCategory)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories={itemCategory}"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
private async void Start() => await StartAsync("men_trousers");

async Task StartAsync(string itemCategory)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories={itemCategory}"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
and will just interpolate the url three times, one for each clothing category
Angius
Angius2y ago
The documentation of the API is how you learn about it
dankmememachine
dankmememachineOP2y ago
Right, this format is new to me, is there something I am missing in terms of docs here? or is it just reading through each GET and seeing what they accept?
Angius
Angius2y ago
Yeah, just see what they accept and what they return
dankmememachine
dankmememachineOP2y ago
Well it just provides an httpclient example from what I can see, and no mention of multiple calls at once:
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://apidojo-hm-hennes-mauritz-v1.p.rapidapi.com/products/list?country=us&lang=en&currentpage=0&pagesize=30&categories=men_trousers"),
Headers =
{
{ "X-RapidAPI-Key", "a807635214msh9feb01fd51a9cf7p19db7ajsnffb480f6b27a" },
{ "X-RapidAPI-Host", "apidojo-hm-hennes-mauritz-v1.p.rapidapi.com" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
this would be for GET products/list I guess it might be hard to really request multiple of the same GET anyway, since I want to basically call one request, get an item from that category, then run the script again with a different request of category Thank you for your help @Angius and @Axiss I'll take a look at optimizing my code and working further on this, I might post a question when it is finalized but I think this is about as much info as I need to continue. Sorry for not knowing much lmao
Axiss
Axiss2y ago
You're welcome!
Angius
Angius2y ago
Anytime
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server