2016-09-05 2 views
0

3 일 전 - Last Topicjson 객체를 얻고 수정하고 게시하려면 어떻게합니까?

나는 json 응답을 받았고 문자열로 변경했습니다. Json Response는 User-Object를 나타냅니다. User-Object 내에서 특정 프로젝트를 검색하여 삭제하려고합니다. 그 후, 나는 HttpPost를 통해 다시 게시하고 싶다. JsonArray의 속성을 저장하여 특정 프로젝트에 대한 검색

private static String getContent(HttpResponse response) { 
HttpEntity entity = response.getEntity(); 
if (entity == null) return null; 
BufferedReader reader; 
try { 
    reader = new BufferedReader(new InputStreamReader(entity.getContent())); 
    String line = reader.readLine(); 
    reader.close(); 
    return line; 
} catch (IllegalStateException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
return null; 

}

String StringResponse = getContent(JsonResponse); 
JSONObject jsonObject = new JSONObject(StringResponse); 
JSONArray ProjectsArray= jsonObject.getJSONArray("projects"); 

. 프로젝트를 삭제

ArrayList<Integer> indexesToRemove = new ArrayList<Integer>(); 
for (int i = 0; i < projectsArray.length; i++) { 
JSONObject current = projectsArray.get(i); 
if (current.get("projectKey") == "**ProjectName**") { 
indexesToRemove.add(i); 
} 
} 

... 완벽하게 작동하고 내 검색 프로젝트가 삭제

for (int i = indexesToRemove.size()-1; i>=0; i--) 
{ 
projectsArray.remove(indexesToRemove.get(i)); 
} 

. 하지만 문제는 HttpPost를 통해 수정 된 UserObject/String을 다시 게시하고 싶다는 것입니다. 그리고 내 삭제 된 프로젝트는 JsonArray "projectsArray"에 있고 처음부터 내 문자열에는 없습니다. 나는

 HttpPost UserChange = new HttpPost (TestUserURL+user); //TODO: 
     UserChange.setHeader("Accept", "application/json"); 
     UserChange.setHeader("Content-type", "application/json"); 

     params = new StringEntity("ModifiedJsonString", HTTP.UTF_8); // How do i get the complete Json string? 
     UserChange.setEntity(params); 

     HttpResponse UserChangeResponse = httpclient.execute(UserChange); 

     HttpEntity entity2 = UserChangeResponse.getEntity(); 
      if (entity2 != null) { 
       entity2.consumeContent();      
      } 

내가 처음부터 완전한 JSON 파일을 포함하는 "ModifiedJsonString"을 필요로 ... "projectsArray"를 게시 할 수 없습니다.

params = new StringEntity(ModifiedJsonString, HTTP.UTF_8); 

안부

답변

0

다음 코드는 선택한 프로젝트 중 하나를 제거합니다.

String jsonString = "{ \"account\": \"Kpatrick\", \"firstname\": \"Patrick\", \"instances\": [  {   \"id\": \"packerer-pool\",   \"key\": \"packerer-pool123\",   \"userAccount\": \"kpatrick\",   \"firstname\": \"Patrick\",   \"lastname\": \"Schmidt\"  } ], \"projects\": [  {   \"id\": \"packerer-projectPool\",   \"projectKey\": \"projectPool-Pool\",   \"cqprojectName\": \"xxxxx\"  },  {   \"id\": \"packerer-secondproject\",   \"projectKey\": \"projectPool-Pool2\",   \"cqprojectName\": \"xxxx\"  },  {   \"id\": \"packerer-thirdproject\",   \"projectKey\": \"projectPool-Pool3\",   \"cqprojectName\": \"xxxx\"  } ], \"clients\": [], \"dbid\": 76864576, \"version\": 1, \"id\": \"dbpack21\"}"; 
JSONParser parser = new JSONParser(); 
JSONObject jsonObject = (JSONObject) parser.parse(jsonString); 

ArrayList<String> listOfNodes = new ArrayList<String>(); 
JSONArray projectArray = (JSONArray) jsonObject.get("projects"); 
int len = projectArray.size(); 
if (projectArray != null) { 
    for (int i = 0; i < len; i++) { 
     String projectId = ((JSONObject) projectArray.get(i)).get("projectKey").toString(); 
     if (!projectId.equals("projectPool-Pool2")) { 
      listOfNodes.add(projectArray.get(i).toString()); 

     } 

    } 
} 
// Remove the element from arraylist 
// Recreate JSON Array 
JSONArray jsArray = new JSONArray(); 
jsArray.addAll(listOfNodes); 
jsonObject.remove(projectArray); 
jsonObject.put("projects", listOfNodes); 

System.out.println(jsonObject.toString()); 

예를 들어 프로젝트 중 하나를 제거하는 다음 JSON 문자열을 인쇄합니다. Linted JSON 이것을 사용하면 이것을 사용하여 StringEntity를 만든 다음 HTTPPost 호출에 사용할 수 있습니다. 희망 도움이

+0

위대한! 답장을 보내 주셔서 감사합니다. 해결책은 다음과 같습니다. jsonObject.put ("projects", listOfNodes); – InfoEngi

관련 문제