This is Our Blog

June 4, 2015
|

How to post and get json data to a service in unity

This article is all about, how to post and get request with json data to a service.

Json Overview

JSON or JavaScript Object Notation is an open standard format that uses human readable text to transmit data objects consisting of attribute-value pair. It is used primarily to transmit data between a server and web application, as an alternative to XML.

Although originally derived from the Java Script scripting language, JSON is a language independent data format. Code for parsing and generating JSON data is readily available in many programming languages.

Implementation

In unity, we use WWW class to send a request. This is a small utility module for retrieving the contents of URLs. The WWW class can be used to send both GET and POST requests to the server. The WWW class will use GET by default and POST if we supply a post Data parameter.

Posting a Get request

To post a get request Create a simple script named GetJsonDataScript. Write the following code and attach the script to Camera.

using UnityEngine;
using System.Collections;

public class GetJsonDataScript : MonoBehaviour
{
    // Use this for initialization
    string Url;
    void Start()
    {
        Url = "Url to the service";
        GetData();
    }

    // Update is called once per frame
    void Update()
    {

    }
    //Invoke this function where to want to make request.
    void GetData()
    {
        //sending the request to url
        WWW www = new WWW(Url);
        StartCoroutine("GetdataEnumerator", Url);
    }
    IEnumerator GetdataEnumerator(WWW www)
    {
        //Wait for request to complete
        yield return www;
        if (www.error != null)
        {
            string serviceData = www.text;
            //Data is in json format, we need to parse the Json.
            Debug.Log(serviceData);
        }
        else
        {
            Debug.Log(www.error);
        }
    }
}

In this script we have made a simple get request, the data received from www.text is in json format we need to parse in to object.

To parse json data into object, we use BoomLagoon asset from unity asset store.


Import Boomlogoon in to unity, Replace the GetJsonDataScript with this script.

using UnityEngine;
using System.Collections;
using Boomlagoon.JSON;
using System;
public class GetJsonDataScript : MonoBehaviour
{
    // Use this for initialization
    string Url;
    Person newPerson;
    void Start()
    {
        Url = "Url to the service";
        newPerson = new Person();
        GetData();
    }
    // Update is called once per frame
    void Update()
    {

    }

    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    //Invoke this function where to want to make request.
    void GetData()
    {
        //sending the request to url
        WWW www = new WWW(Url);
        StartCoroutine("GetdataEnumerator", Url);
    }

    IEnumerator GetdataEnumerator(WWW www)
    {
        //Wait for request to complete
        yield return www;
        if (www.error != null)
        {
            string serviceData = www.text;
            //Data is in json format, we need to parse the Json.
            Debug.Log(serviceData);
            JSONObject json = JSONObject.Parse(serviceData);
            if (json == null)
            {
                Debug.Log("No data converted");
            }
            else
            {
                //now we can get the values from json of any attribute.
                newPerson.Id = Convert.ToInt32(json["Id"].Number);
                newPerson.Name = json["Name"].Str;
            }
        }
        else
        {
            Debug.Log(www.error);
        }
    }
}

 

In this script we have simply made a request, get the data from WWW
class and parse the service result into Person class object with Boomlagoon.JSON. If web service returns json array then replace the IEnumerator with following code.

List persons;
IEnumerator GetdataEnumerator(WWW www)
{
    //Wait for request to complete
    yield return www;
    if (www.error != null)
    {
        string serviceData = www.text;
        //Data is in json format, we need to parse the Json.
        Debug.Log(serviceData);
        JSONArray jsonArray = JSONArray.Parse(www.text);
        if (jsonArray == null)
        {
            Debug.Log("No data converted");
        }
        else if (jsonArray.Length > 0)
        {
            //create a list for storing the details or persons
            persons = new List();
            //now we can get the values from json of any attribute.
            for (int i = 0; i < jsonArray.Length; i++)
            {
                newPerson.Id = Convert.ToInt32(jsonArray[i].Obj["Id"].Number);
                newPerson.Name = jsonArray[i].Obj["Name"].Str;
            }
        }
    }
    else
    {
        Debug.Log(www.error);
    }
}

Posting a Post request

To post a get request we have to pass post Data parameter. To pass post Data parameter we use WWWForm class. It is a
helper class to generate form data to post to web servers using the
 WWW
 class. In order to do that, Create a simple script named PostJsonDataScript. Write the following code and attach the script to Camera.

using UnityEngine;
using System.Collections;

public class PostJsonDataScript : MonoBehaviour
{
    // Use this for initialization
    string Url;
    void Start()
    {
        Url = "Url to the service";
        PostData(100,"Unity");
    }
    // Update is called once per frame
    void Update()
    {

    }
    void PostData(int Id,string Name)
    {
        WWWForm dataParameters = new WWWForm();
        dataParameters.AddField("Id", Id);
        dataParameters.AddField("Name", Name);
        WWW www = new WWW(Url,dataParameters);
        StartCoroutine("PostdataEnumerator", Url);
    }
    IEnumerator PostdataEnumerator(WWW www)
    {
        yield return www;
        if (www.error != null)
        {
            Debug.Log("Data Submitted");
        }
        else
        {
            Debug.Log(www.error);
        }
    }
}

If you want to pass a json array to the service.Then replace the PostJsonDataScript with this script.

using UnityEngine;
using System.Collections;
using System.Text;

public class PostJsonDataScript : MonoBehaviour
{
    // Use this for initialization
    string Url;
    void Start()
    {
        Url = "Url to the service";
        PostData();
    }
    // Update is called once per frame
    void Update()
    {

    }
    void PostData()
    {
        string JsonArraystring = "{\"Persons\": [{\"Id\":\"101\",\"Name\":\"Unity4.6\"},{\"Id\":\"102\",\"Name\":\"Unity5\"}]}";
        Hashtable headers = new Hashtable();
        headers.Add("Content-Type", "application/json");
        byte[] body = Encoding.UTF8.GetBytes(JsonArraystring);
        WWW www = new WWW(Url, body, headers);
        StartCoroutine("PostdataEnumerator", www);
    }
    IEnumerator PostdataEnumerator(WWW www)
    {
        yield return www;
        if (www.error != null)
        {
            Debug.Log("Data Submitted");
        }
        else
        {
            Debug.Log(www.error);
        }
    }
}

Thank you. If you have any query can write me mail on Lalit.kumar@devinit.ch , it would help us a lot.




12 Comments

  1. Reply

    Yes! Finally someone writes about máy lọc không khí panasonic f-pxf35a.

  2. Reply

    omer

    May 16, 2016

    i used your code .. works great on the editor but on device it doesn't work ? kindly help

  3. Reply

    tim

    June 8, 2016

    should these codes be edited?

    if (www.error != null)
    {
    Debug.Log("Data Submitted");
    }
    else
    {
    Debug.Log(www.error);
    }

    != --> ==

  4. Reply

    haitham

    June 15, 2016

    i want to send to server {"username":"username" , "password":"password"}

    and receive json like this { "status": "1" "name": "user name" "statusMessage": "Login Successfully" "type": "user" "mode": "" "expireDate": "" }

    server already have the configuration and works fine coz i tested it on my Android application (Android studio) but i don't know how to do the same with unity

    thanks

  5. Reply

    Alex

    March 7, 2017

    Hi,

    I was testing your code but in "Posting a Post request"
    i got an error:
    MissingMethodException: The best match for method postDataEnumerator has some invalid parameter.
    System.MonoType.InvokeMember (System.String name, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object target, System.Object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParameters) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/MonoType.cs:520)
    UnityEngine.SetupCoroutine.InvokeMember (System.Object behaviour, System.String name, System.Object variable) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:31)
    UnityEngine.MonoBehaviour:StartCoroutine(String, Object)
    postJsonData:postData(String) (at Assets/Scripts/postJsonData.cs:37)
    postJsonData:Start() (at Assets/Scripts/postJsonData.cs:12)

    i believe it is because you say "StartCoroutine("PostdataEnumerator", Url);" but when i change Url to www everything works?

    Am I crazy?

    • Reply

      Alex

      March 7, 2017

      Ah by the way, i was sending a string and a wav file to the server and not just 2 strings :)

  6. Reply

    Adrian

    February 11, 2018

    Since 1 week i was serching for solution on my Json problem, and i suddenly came here and it was my solution, thank you very much this works perfectly

  7. Reply

    promote fan page

    February 14, 2018

    Appreciate almost every other insightful web site promote fan page. Where in addition may I buy that kind expertise designed in such an great style? I have a mission that we're at the moment implementing, and I've already been within the be aware of similarly info.

  8. Reply

    hataythoi.info

    May 10, 2018

    Hiya very cool web site!! Guy .. Beautiful ..
    Superb .. I'll bookmark your website and take thhe feeds additionally?
    I amm happy to find numerous helpful info right here in the put up, we need work out extra techniques
    in this regard, thank you for sharing. . .
    . . .

  9. Reply

    Flooring

    March 5, 2019

    No matter if some one searches for his vital thing, therefore he/she desires to be available that in detail,
    thus that thing is maintained over here.

  10. Reply

    Kitchen set Pondok Cabe

    April 2, 2019

    Аt this time it looks lіke Expression Engine is the top bⅼoɡging platform avaіlable
    riɡht now. (from what I've rеad) Is that ԝhat you'гe using on your blog?

  11. Reply

    wonderful put up, very informative. I ԝonder whу the opposite
    specialists of this sector dоn't understand tһis.
    Үоu must proceed ʏour writing. I'm confident, yⲟu've ɑ gгeat readers' base аlready!


Would you like to share your thoughts?

Would you like to share your thoughts?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.