说我想提出以下JSON
Say I want to make the following JSON
{
"key" : "1234",
"request" : "info",
"info" : {
"type" : "user",
"login" : {
"username" : "some_username",
"password" : "some_password"
}
}
}
目前,这是我如何实现它
Currently, this is how I'm achieving it
//Construct the JSON
JSONObject json = new JSONObject();
JSONObject info_json = new JSONObject();
JSONObject login_info = new JSONObject();
try
{
login_info.put("username", "some_username");
login_info.put("password", "some_password");
info_json.put("type", "user");
info_json.put("login", login_info);
json.put("key", "1234");
json.put("request", "info");
json.put("info", info_json);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("JSON could not be made");
}
这似乎应该这样做,而不是让更多的 JSONObjects
,并把他们在主 JSON对象。有没有更好的方式来在比我现在用的方法,动态构造这些?
It seems there should be a better way of doing this instead of making more JSONObjects
, and placing them in a main JSON Object
. Is there a better way to construct these on the fly than the method I am using?
在此先感谢您的帮助!
推荐答案
如果你的工作有很多使用JSON数据我真的建议你使用的 GSON 或杰克逊。这是一个很多更方便,这两个库都转换和从Java对象(这是少了很多混乱的,容易出错不是通过JSONObjects手动构建JSON)很好的支持。
If you work a lot with JSON data I would really recommend that you use Gson or Jackson. It's a lot more convenient and both of the libraries have very good support for converting to and from Java objects (which is a lot less messy and error prone than manually building your JSON through JSONObjects).
相关推荐
最新文章