Mridul Pareek
Mridul Pareek

Reputation: 1

Unity3D, creating a Json post request

I have to create a post request in Json in this format.

{
"request": {
    "application": "APPLICATION_CODE",
    "auth": "API_ACCESS_TOKEN",
    "notifications": [{
        "send_date": "now", // YYYY-MM-DD HH:mm  OR 'now'
        "ignore_user_timezone": true, // or false
        "content": "Hello world!"
    }]
}
}

This is my first time serializing Json String and I have no idea how to do this, I have tried a few different things but could never get the exact format.

Would really appreciate any kind of help.

Thanks!

Upvotes: 0

Views: 70

Answers (2)

OsmanSenol
OsmanSenol

Reputation: 146

You can also use SimpleJSON like this ;

string GetRequest () {
    JSONNode root = JSONNode.Parse("{}");

    JSONNode request = root ["request"].AsObject;
    request["application"] = "APPLICATION_CODE";
    request["auth"] = "API_ACCESS_TOKEN";

    JSONNode notification = request ["notifications"].AsArray;
    notification[0]["send_date"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
    notification[0]["ignore_user_timezone"] = "true";
    notification[0]["content"] = "Hello world!";

    return root.ToString ();
}

Upvotes: 0

Everts
Everts

Reputation: 10721

First, you cannot put comment on a json file, but I guess it was just there for now.

Then you can paste your json in converters like this one http://json2csharp.com/ And you get the following:

public class Notification
{
    public string send_date { get; set; }
    public bool ignore_user_timezone { get; set; }
    public string content { get; set; }
}

public class Request
{
    public string application { get; set; }
    public string auth { get; set; }
    public List<Notification> notifications { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
}

Now you need to fix a few issues that are required for JsonUtility:

[Serializable]
public class Notification
{
    public string send_date;
    public bool ignore_user_timezone;
    public string content;
}
[Serializable]
public class Request
{
    public string application;
    public string auth;
    public List<Notification> notifications;
}
[Serializable]
public class RootObject
{
    public Request request;
}

Finally:

RootObject root = JsonUtility.FromJson<RootObject>(jsonStringFile);

Upvotes: 1

Related Questions