2012-07-27 3 views
0

JSON으로 바꾸고 싶은 클래스가 있지만 생성자가 나를 허용하지 않습니다. 클래스가 CourseKeyInfo라고 :자바에서 콩을 Json으로 바꾸기

public class CourseKeyInfo 
{ 
    private String courseKey; 
    private String institutionID; 
    public CourseKeyInfo(String courseKey, String institutionId) 
    { 
     this.courseKey = courseKey; 
     this.institutionID = institutionId; 
    } 
    public String getCourseKey() 
    { 
     return courseKey; 
    } 
    public void setCourseKey(String courseKey) 
    { 
     this.courseKey = courseKey; 
    } 
    public String getInstitutionID() 
    { 
     return institutionID; 
    } 
    public void setInstitutionID(String institutionID) 
    { 
     this.institutionID = institutionID; 
    } 
} 

내가 JSON로를 설정하는 JSONObject body = new JSONObject(responseEntity);를 사용하지만이 날 줄 오류 "생성자 된 JSONObject (CourseKeyInfo)는 정의되지 않는다." 내 수업을 어떻게 json으로 바꿀 수 있는지 아는가? HTTP 요청에 대한

+0

는 당신이 http://www.json.org/javadoc/org/json/JSONObject.html를 사용하는이 API인가? – Nishant

+0

그렇다면 http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29를 지원해야합니다. 생성자에서 Object가 걸립니다. – Nishant

+0

Nishant가 옳습니다. Jettison 구현을 사용하고 있으며 올바른 API를 사용하지 않았습니다. 나는 org.json으로 바꿨고 효과가 있었다. – user1558274

답변

1

여기에 JSON 배열 + JSON 콩

JSONArray jsonArray = new JSONArray(); 
    for (Credentials credentials : ((PropertiesManager) propertiesManager.get()).getJsonPropertiesManager().getAllCredentials()) { 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.put("credentialsName", credentials.getName()); 
     jsonArray.add(jsonObject); 
    } 

    req.setAttribute(JSON_RESULT_OBJ_ATTR, jsonArray.toString()); 
2

JSONObject(Object)이 존재 실제로 않는 생성자를 사용하는 예입니다.

CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101"); 
JSONObject jsonObject = new JSONObject(courseKeyInfo); 
+0

그 링크는 404 오류를 보여줍니다. 고쳐주세요. – Shashanth

+1

@Shashanth는 업데이트 된 링크입니다.) – Reimeus

0

당신이 GSON를 사용하는 경우, 당신은이 작업을 수행 할 수는 그대로 한 줄이에 대한

CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101"); 
String json = new Gson().toJson(courseKeyInfo); 
System.out.println(json); 

  • 다운로드 GSON JAR
  • 프로젝트 빌드 경로
  • 에 추가 작업
  • 그게 전부 야.

그 결과는 다음과 같습니다

{"courseKey":"This Works!","institutionID":"101"} 
관련 문제