2016-11-26 130 views
0

我要创建一个JSON POST请求在这种格式。Unity3D,创建一个JSON post请求

{ 
"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!" 
    }] 
} 

}

这是我第一次序列化JSON字符串,我不知道如何做到这一点,我已经尝试了一些不同的东西,但永远无法得到确切的格式。

真的很感谢任何形式的帮助。

谢谢!

回答

1

首先,你不能把一个JSON文件发表评论,但我想这只是在那里了。

然后你就可以粘贴JSON在这样一个http://json2csharp.com/ 转换器,你会得到如下:

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; } 
} 

现在你需要修复所必需的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; 
} 

最后:

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

太谢谢你了!我会试试看,并回复你! :) –

0

你也可以使用SimpleJSON这样;

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(); 
}