Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    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));