2012-07-27 93 views
0

我有一個我想變成JSON的類,但構造函數不允許我。該類稱爲CourseKeyInfo:在java中將bean轉換爲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; 
    } 
} 

我用JSONObject body = new JSONObject(responseEntity);把它變成JSON,但它給我「的構造函數的JSONObject(CourseKeyInfo)是未定義」的錯誤。任何想法如何我可以把我的課變成json?

+0

難道這個API使用的是http://www.json.org/javadoc/org/json/JSONObject.html? – Nishant 2012-07-27 17:09:01

+0

如果是這樣,它應該支持這個http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29它在構造函數 – Nishant 2012-07-27 17:11:09

+0

中需要Object Nishant你是對的。我使用的是Jettison實現,我沒有使用正確的API。我將其更改爲org.json並且它工作正常。 – user1558274 2012-07-27 17:21:17

回答

1

爲http請求這裏是例如使用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 2017-07-10 06:51:10

+1

@Shashanth只爲你在這裏是更新的鏈接;) – Reimeus 2017-07-10 09:27:19

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"}