如何使Java中的嵌套JSON对象?嵌套、对象、Java、JSON

2023-09-05 10:14:17 作者:重头再来

我要编一个嵌套的JSON对象为我的Andr​​oid设备,但如何?我只有使用JSON基本经验,所以我会AP preciate如果有人可以帮助我下面的code:

  {
 命令:登录,
 UID:123123123,
 PARAMS:
  {
   用户名:SUP,
   密码:兄弟
  }
}
 

编辑:

下面code确实解决问题:

  loginInformation =新的ArrayList<的NameValuePair>();

JSONObject的parentData =新的JSONObject();
JSONObject的childData =新的JSONObject();

尝试 {

    parentData.put(命令,密码);
    parentData.put(UID,UID.getDeviceId());

    childData.put(用户名,username.getText()的toString());
    childData.put(密码,password.getText()的toString());
    parentData.put(PARAMS,childData);

}赶上(JSONException E){
    e.printStackTrace();
}

loginInformation.add(新BasicNameValuePair(内容,parentData.toString()));
 

解决方案 如何查看一个 Java 对象的大小

您需要创建一个 JSON ,并添加 JSON 在你的 POST 的参数。要做到这一点你应该:

  post.add(新BasicNameValuePair(数据,json.toString());
 

您可以使用 org.json.JSONObject ,它包含在 Android SDK中

I want to program a nested JSON Object for my Android device, but how? I have only basic experience with Json, so I would appreciate if someone could help me with the following code:

{ 
 "command": "login",
 "uid": "123123123",
 "params":
  {
   "username": "sup",
   "password": "bros"
  }
}

Edit:

The following code does solve the problem:

loginInformation = new ArrayList<NameValuePair>(); 

JSONObject parentData = new JSONObject();
JSONObject childData = new JSONObject();

try {

    parentData.put("command", "login");
    parentData.put("uid", UID.getDeviceId());

    childData.put("username", username.getText().toString());
    childData.put("password", password.getText().toString());
    parentData.put("params", childData);

} catch (JSONException e) {
    e.printStackTrace();
}

loginInformation.add(new BasicNameValuePair("content", parentData.toString()));

解决方案

You need to create a JSON, and add that JSON as a parameter in your POST. To do that you should probably :

post.add(new BasicNameValuePair("data",json.toString());

You could use org.json.JSONObject, it is included in the Android SDK.