2010-10-08 40 views
1

我正在製作一個主要用JavaScript和Flash編寫的LinkedIn應用程序,但所有數據都來自Java代理。我需要使用JSON數據,不幸的是,LinkedIn只支持XML。最好的解決方案是在將XML發送回客戶端之前將XML轉換爲JSON,但我承認我的Java技能並不強大。我有看起來應該工作的代碼,但我得到一個JSONObject異常。將LinkedIn XML數據轉換爲Java中的JSON

我使用org.json包來操作XML:http://json.org/java/

這是一種嘗試XML轉換成JSON的Java代碼。這不是很漂亮,但我只是想取得一些進展與轉換數據:

public static String readResponse(HttpResponse response) { 
    System.out.println("Reading response..."); 

    try { 
     BufferedReader br = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 
     String readLine; 
     String innhold = ""; 

     while (((readLine = br.readLine()) != null)) { 
      innhold += readLine; 
     } 

     try { 
      JSONObject myJ = new JSONObject(); 
      String ret = myJ.getJSONObject(innhold).toString(); 
      System.out.println(ret); 

      return ret; 
     } catch (Exception e) { 
      System.out.println(e); 
     } 

     return innhold; 
    } catch (IOException e) { 
     System.out.println(e); 
     return null; 
    } 
} 

下面是數據非常相似,我想轉換:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<person> 
    <first-name>First</first-name> 
    <last-name>Last</last-name> 
    <headline>My Profile</headline>  
    <site-standard-profile-request>  
    <url>http://www.linkedin.com/profile</url> 
    </site-standard-profile-request> 
</person> 

這裏是異常我越來越:

org.json.JSONException: JSONObject["<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><person> <first-name>First<\/first-name> <last-name>Last<\/last-name> <headline>My Profile<\/headline> <site-standard-profile-request> <url>http://www.linkedin.com/profile<\/url> <\/site-standard-profile-request><\/person>"] not found. 

任何幫助表示讚賞,謝謝!

回答

0

看起來你正在使用錯誤的對象和方法。 JSONObject.getJSONObject()希望您提供一個密鑰來查找對象,而不是任何arbritrary XML字符串。

您沒有與該XML字符串匹配的鍵,因此查找失敗,並且您得到的對象(使用指定鍵)未找到的異常。

您試圖解析XML並將其序列化爲JSON。

我相信你可以使用XML.toJSONObject

1

的Mads,那就是這樣做的伎倆!非常感謝,我知道有一個非常簡單的解決方案,我只是沒有看到。這是將XML字符串轉換爲JSON的神奇行:

String ret = XML.toJSONObject(aStringOfXml).toString();