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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    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));