1

我正在制作一个主要由 JavaScript 和 Flash 编写的 LinkedIn 应用程序,但所有数据都来自 Java 代理。我需要 JSON 格式的数据,不幸的是 LinkedIn 只支持 XML。最好的解决方案是在服务器上将 XML 转换为 JSON,然后再将其发送回客户端,但不可否认,我的 Java 技能并不强。我的代码看起来应该可以工作,但我得到了 JSONObject 异常。

我正在使用 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.

任何帮助表示赞赏,谢谢!

4

2 回答 2

1

麦德斯,这只是把戏!非常感谢,我知道有一个非常简单的解决方案,我只是没有看到。这是将 XML 字符串转换为 JSON 的神奇行:

String ret = XML.toJSONObject(aStringOfXml).toString();
于 2010-10-09T15:54:11.747 回答
0

看起来您使用了错误的对象和方法。 JSONObject.getJSONObject() 期望您提供一个键来查找一个对象,而不是一个任意的 XML 字符串。

您没有与该 XML 字符串匹配的键,因此查找失败并且您收到未找到对象(具有指定键)的异常。

您正在尝试解析 XML 并序列化为 JSON。

我相信你可以使用XML.toJSONObject

于 2010-10-09T01:57:48.227 回答