Reputation: 1
I am beginner in android so pls help me, i want to extract json array from xml parsing string which is below:
<?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>
How we can get json string from above string in android, help me.
Upvotes: 0
Views: 795
Reputation: 6614
here is solution with GSON
here i tried to parse the xml to get the json string and then parse the json to get the necessary elements from that
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();
}
Note: - (ofcourse you can try without GSON and use native JSON parser )
Upvotes: 1