Home > OS >  Pass a string instead of type in JsonUtility.FromJson<>()
Pass a string instead of type in JsonUtility.FromJson<>()

Time:09-03

So I've been learning how to make asynchronous multiplayer games, cool stuff.

To make my code look better I wanted to be able to pass a class name as a string, this would make my code a lot better to read because I could use this function for my requests:

public IEnumerator DoWebRequest(string url, string jsonData, string classToPass)
{
    WWWForm _form = new WWWForm();
    _form.AddField("json", jsonData);
    using (UnityWebRequest _webRequest = UnityWebRequest.Post(url, _form))
    {
        yield return _webRequest.SendWebRequest();

        var _response = JsonUtility.FromJson<StringHerePls> (_webRequest.downloadHandler.text);
        //Debug.Log("LocationX: "   _response.locationX   " LocationY: "   _response.locationY   " LocationZ: "   _response.locationZ);
    }
}

I've tried using:

  • System.Type.GetType(classToPass)
  • System.Type.GetType(classToPass).MakeGenericType(classToPass);
  • Variations of the above include making it a local variable and using that variable.

The error I get when using the mentioned System.Type.GetType(classToPass):

  • Operator '<' cannot be applied to operands of type 'method group' and 'Type'

To try out if this conversion worked at all I tried using:

var _response = JsonUtility.FromJson< System.Type.GetType(classToPass) > (_webRequest.downloadHandler.text);

to get a reference to a script, this did work.

So I'm at a loss for how to get this to work, I just don't get why the GetComponent did work but the FromJason did not.

CodePudding user response:

public struct Response 
{
    public locationX ;
    public locationY ; 
    //....
}

Response _response = JsonUtility.FromJson<Response> (_webRequest.downloadHandler.text);

CodePudding user response:

You can use the JsonUtility.FromJson(string, Type) overload and use reflection to find a Type with name matching classToPass.

Something like this:

Type type = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).SelectMany(a => assembly.GetExportedTypes()).First(t => t.Name == classToPass);

var response = JsonUtility.FromJson(_webRequest.downloadHandler.text, type);
  • Related