0

我是android的初学者,所以请帮助我,我想从下面的xml解析字符串中提取json数组:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"id":3033,"type":"cpt4","description":"New Patient Office Visit  for Moderate to Severe problems- Requiring Longer Visit","category":"Office Visits","subCategory":"Illness Related Visits","inNetwork":195.99,"outNetwork":424.06,"code":"99205","zip":"90210","lastupdated":"2012-02-13T00:00:00.000-05:00"}]
</string>

我们如何在android中从上面的字符串中获取json字符串,帮助我。

4

1 回答 1

1

这是GSON的解决方案

  • 从上面的链接下载GSON jar 将其添加到您的构建路径

在这里,我尝试解析 xml 以获取 json 字符串,然后解析 json 以从中获取必要的元素

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">"
        + "[{\"id\":3033,\"type\":\"cpt4\",\"description\":\"New Patient Office Visit  for Moderate to Severe problems- "
        + "Requiring Longer Visit\",\"category\":\"Office Visits\",\"subCategory\":\"Illness Related Visits\","
        + "\"inNetwork\":195.99,\"outNetwork\":424.06,\"code\":\"99205\",\"zip\":\"90210\",\"lastupdated\":\"2012-02-13T00:00:00.000-05:00\"}]"
        + "</string>";

Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    doc = db.parse(is);
} catch (Exception e) {
    e.printStackTrace();
}

doc.getDocumentElement().normalize();
String text = doc.getDocumentElement().getTextContent();
System.out.println(text);

try {
    // testing whether the json string is valid or not
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(text);
    System.out.println("Valid JSon");

    System.out.println("isArray : " + jsonElement.isJsonArray());

    JsonArray jsonArray = jsonElement.getAsJsonArray();
    JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
    System.out.println("id : " + jsonObject.get("id"));
    System.out.println("type : " + jsonObject.get("type"));
    System.out
            .println("description : " + jsonObject.get("description"));
    System.out.println("category : " + jsonObject.get("category"));
    System.out
            .println("subCategory : " + jsonObject.get("subCategory"));
    System.out.println("inNetwork : " + jsonObject.get("inNetwork"));
    System.out.println("outNetwork : " + jsonObject.get("outNetwork"));
    System.out.println("code : " + jsonObject.get("code"));
    System.out.println("zip : " + jsonObject.get("zip"));
    System.out
            .println("lastupdated : " + jsonObject.get("lastupdated"));

} catch (JsonSyntaxException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
}       

注意:-(当然你可以尝试不使用 GSON 并使用原生 JSON 解析器)

于 2012-07-13T12:29:27.260 回答