如何使用java从API返回JSON返回的每个值

时间:2016-03-20 15:24:58

标签: java json

{  
   status:"success",
   user:{  
      id:"86",
      user_id:"83",
      user_profile_id:"777",
      first_name:"xxxx",
      last_name:"x1",
      full_name:"cccc2",
      country:"IN",
      state:"Karnataka",
      city:"Bangalore Urban",
      zip:"560052",
      timezone:null,
      timezone_id:null,
      photo:null,
      import_key:null,
      date_update:null,
      role:"22",
      status:"10",
      email:"mail@gmail.com",
      email_is_confirmed:"1",
      reg_date:"2016-03-18 11:08:32",
      last_login_date:"2016-03-18 11:10:40"
   },
   token:"iuwehry723ibf8f289ryfhu",
   saved:"0"
}

我的API返回上面的输出。如何打印每个值如下:

id = 86
user_id = 83

2 个答案:

答案 0 :(得分:0)

首先,您需要拥有该库...您可以找到它here This就是你在这个库中的内容

您下载它,解压缩并将jar文件复制到您的项目中,然后右键单击它并将其添加到您的构建路径

如果你在字符串中有json,你可以这样做

// Load the json string as an Json object
JSONObject obj = new JSONObject(yourStringJson);


// Extract from this object whatever is in

// if is a String
String status = obj.getString("status");

// if is another object, you get the object first and the whatever is inside
String id = obj.getJSONObject("user").getString("id");
String userId = obj.getJSONObject("user").getString("user_id");
.....

// and so on
String token = obj.getString("token");

答案 1 :(得分:0)

您可以使用Goolge Gson api打印您的Json对象

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>1.7.1</version>
</dependency>

Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);