Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

json usage for noob

Discussion in 'Scripting' started by beppim, Feb 17, 2017.

  1. beppim

    beppim

    Joined:
    Jul 2, 2015
    Posts:
    58
    I apologize if the question is too simple.

    I just received a response as byte[] from a webClient POST request.
    This response is a json, I want to simply get one of the fields.

    WebClient client = new WebClient();
    byte[] response = client.UploadValues(baseUrlAdd, new NameValueCollection()
    {
    { "Device_ID", Globals.device_id },
    });

    object[] result = JsonUtility.FromJson<object[]>(System.Text.Encoding.Default.GetString(response));
    Globals.game_id = result["Game_ID"]; // ???????????

    This is wrong. How do I get "Game_ID" ?

    Thank you!
     
  2. gaweph

    gaweph

    Joined:
    Sep 2, 2012
    Posts:
    26
    Can you cast as dynamic or the Type (if you have it) instead of object[]?

    (At work, but something like this should work)
    e.g.
    dynamic result = JsonUtility.FromJson<dynamic>(System.Text.Encoding.Default.GetString(response));

    var gameID = result.GAMEID (not sure on what this will be exactly).
     
  3. beppim

    beppim

    Joined:
    Jul 2, 2015
    Posts:
    58
    yes, if I cast it to dynamic it doesn't give me syntax error anymore, so this:

    dynamic stuff = JsonUtility.FromJson<dynamic>(System.Text.Encoding.Default.GetString(response));
    Globals.game_id = stuff.Game_ID;

    should work?
     
  4. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    It should, but there is always a doubt. If you know the structure of what you are deserializing, you can always create the object needed to deserialize it to.

    Code (csharp):
    1. public class ObjectName{
    2. public int Game_ID {get;set;}
    3. }
    4.  
    5. then...
    6. ObjectName stuff = JsonUtility.FromJson<ObjectName>(System.Text.Encoding.Default.GetString(response));