如何读取在线存储的 json 文件并在找到时将图像更改为 url

How to read a json file stored online and change image to url when found

我正在统一制作一个应用程序,我需要用户搜索关键字,它将 return 存储在与该关键字相关的在线 json 文件中的所有图像网址(slug )

我的同事给我写了下面的代码,因为她对语言的了解比我多,但她不使用 unity,我不知道它是否适合 unity 或改变图像的纹理,因为我不会似乎触发它。 json 文件当前存储在项目中,但我希望它能阅读在线内容。

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

您可以使用WebClient下载远程文件的内容:

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

请注意,根据您使用的 .NET 配置文件,您可能需要为 System.Net.WebClient.dll 和 System.Net.dll 添加程序集引用。您可以找到有关如何添加程序集引用的更多详细信息 here.