【问题标题】:transfer json to xml in java在java中将json转换为xml
【发布时间】:2015-01-23 12:25:47
【问题描述】:

我正在尝试将 json 传输到 xml 文件,但出现问题。

代码示例:

  String strinput= query;
    ArrayList<String> urls = new ArrayList<>();
    String keyofaccount = "mykey";
    String bingApiUrlpattern = "https://api.datamarket.azure.com/Bing/Search/Web?Query=%%27%s%%27&$format=JSON";

    String query = URLEncoder.encode(strinput, Charset.defaultCharset().name());
    String bingUrl = String.format(bingApiUrlpattern, query);

    byte[] accountkeyinbytes = Base64.encodeBase64((keyofaccount + ":" + keyofaccount).getBytes());
    String accountkeyencryp = new String(accountkeyinbytes);
    URL url = new URL(bingUrl);
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("Authorization", "Basic " + accountkeyencryp);

    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())))
    {
        String inputLine;

        StringBuilder stringbuilder = new StringBuilder();
        while ((inputLine = in.readLine()) != null)
        {
            stringbuilder.append(inputLine);
        }

        JSONObject job= new JSONObject(stringbuilder.toString());
        String xmstr = org.json.XML.toString(job);
        System.out.println(xmlstr);
    }
    catch (JSONException e)
    {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

我得到的结果:

<d><results><Description>Give your home, office and life good feng shui with expert advice from Rodika Tchi. Learn about feng shui elements, Chinese zodiac, birthstones &amp; more.</Description><Url>http://fengshui.about.com/</Url><DisplayUrl>fengshui.about.com</DisplayUrl><ID>48333f88-d9e7-4b01-913c-4b8e65e28878</ID><__metadata><type>WebResult</type><uri>https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=&apos; feng shui&apos;&amp;$skip=0&amp;$top=1</uri></__metadata><Title>Feng Shui - Expert Tips and Advice - About.com</Title></results><results><Description>Feng shui (i pinyin: fēng shuǐ) is a Chinese philosophical system of harmonizing everyone with the surrounding environment. The term feng shui literally translates ...</Description><Url>http://en.wikipedia.org/wiki/Feng_shui</Url>....

有谁知道我的问题在哪里? 我怎样才能只得到描述?

【问题讨论】:

  • 你能描述一下结果有什么问题吗?它看起来像有效的 XML(快速浏览)
  • 如果您不向我们展示原始 JSON 格式的数据,我们怎么知道问题出在哪里?正如我所看到的(但我没有对其进行长时间的分析),它似乎可以工作,您的输出看起来像 XML,您所说的“出现问题”是什么意思?
  • 例如,如果我搜索查询“卢浮宫在哪里?”。我没有得到关于位置的详细信息,我不认识它。

标签: java xml json


【解决方案1】:

您正在打印整个 XML 字符串 - 您如何期望它只提供描述?为此,您需要使用类似

的方式解析 JSON 数据或 XML
JSONArray results = job.getJSONObject("d").getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
    System.out.println(results.getJSONObject(i).get("Description"));
}

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 2013-06-01
    • 1970-01-01
    • 2020-09-23
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多