0

私はAndroidの初心者なので、plsが私を助けてくれます。以下の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 に答える