Java 读取JSON文件并显示其内容
我的Unix机器上有test.json文件,其数据如下Java 读取JSON文件并显示其内容,java,json,Java,Json,我的Unix机器上有test.json文件,其数据如下 { "recordId" :10, "recordName" : "RECORDS", "records" : [ { "field1" : 111, "titleField" : 1, "titleIDMap" : null, "titleId" : 500, "titleStartDate" : "2013-12-22T00:00:00.000+0000", "titleEnd
{
"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
}]
}
现在,我正在编写RESTJersey客户端来读取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并显示其内容
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("recordId");
System.out.println(name);
对于记录
:
List<String> list = new ArrayList<String>();
JSONArray jsonList = jsonObject.getJSONArray("records");
for (int i = 0; i < jsonList.length(); i++)
list.add(jsonList.getString(i));
List List=new ArrayList();
JSONArray jsonList=jsonObject.getJSONArray(“记录”);
for(int i=0;i
您的
记录
数据将在列表
对象中@Kamlesh_Arya感谢abt打印records@Kamlesh_AryapostJSONData的回报是什么