I am making an app in unity and i need the user to search for a keyword and it will return all the imageurls stored in an online json file that relate to that keyword (slug)
My colleague wrote me the below code, as she has way more knowledge with the language than me, but she doesnt use unity and i dont know if its suitable for unity or changing the texture of the image, as i cant seem to trigger it. The json file is currently stored in the project, but i would prefer it to read something that is online.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (StreamReader r = new StreamReader("Assets/document.json"))
{
string json = r.ReadToEnd();
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
[Serializable]
class ArtImage
{
public string name { get; set; }
public string imageurl { get; set; }
}
You can use WebClient to download content of remote file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;
public class UrlOpener : MonoBehaviour
{
public string imageaddress;
public void Open()
{
using (var client = new WebClient())
{
string json = client.DownloadString("http://www.example.com/some.json");
var img= JsonUtility.FromJson<ArtImage>(json);
imageaddress = img.imageurl;
}
}
}
Note that depending on .NET profile you are using, you may need to add assembly references for System.Net.WebClient.dll and System.Net.dll. You can find more details on how to add assembly references here.