我的Unix机器上有test.json文件,其中包含以下数据
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"field1" : 111,
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
现在我正在编写 REST jersey客户端来阅读test.json并显示输出如下
public class RestWebServiceClient {
private static String BASE_URL="https://myUrl.com";
public static void main(String[] args) {
JSONParser parser = new JSONParser();
final String auth = "mfndfkndfkdnfkdnfdkfndkfndfkndkfndzxzxzxz==";
try {
Object obj = parser.parse(new FileReader("/home/user/test.json"));
JSONObject jsonObject = (JSONObject) obj;
final String postData = "dataTobePosted";
final String postResult = postJSONData(auth, BASE_URL+"/search",postData);
System.out.println("\n============postResponse============");
System.out.println(postResult);
JSONObject issueObj = new JSONObject(postResult);
}
catch (AuthenticationException e){
System.out.println("Username or Password wrong!");
e.printStackTrace();
} catch (JSONException e) {
System.out.println("Invalid JSON output");
e.printStackTrace();
} catch (ClientHandlerException e) {
System.out.println("Error invoking REST method");
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String postJSONData(String auth, String url, String data) throws AuthenticationException, ClientHandlerException{
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").post(ClientResponse.class, data);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
return response.getEntity(String.class);
}
如何阅读test.json并显示其内容?
答案 0 :(得分:1)
recordId
:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("recordId");
System.out.println(name);
records
:
List<String> list = new ArrayList<String>();
JSONArray jsonList = jsonObject.getJSONArray("records");
for (int i = 0; i < jsonList.length(); i++)
list.add(jsonList.getString(i));
您的records
数据将位于list
对象