gpt4 book ai didi

java - 在 Java 中将 LinkedIn XML 数据转换为 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:25 24 4
gpt4 key购买 nike

我正在制作一个主要由 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.

感谢任何帮助,谢谢!

最佳答案

Mads,这确实成功了!非常感谢您,我知道有一个非常简单的解决方案,但我没有看到。下面是将 XML 字符串转换为 JSON 的神奇行:

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

关于java - 在 Java 中将 LinkedIn XML 数据转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3894470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com