
มี project ที่ต้องใช้ SOAP Interface เวลา Request ไป จะได้ Response กลับมาในรูปแบบ XML ตามภาพเลยครับ วันนี้ก็มาแนะนำ Android Library ตัวหนึ่งชื่อ XmlToJson เอาไว้แปลง xml to json
1.การติดตั้ง ที่ไฟล์ build.gradle (Module: app)
เพิ่ม repositories
1 2 3 4 5 |
allprojects { repositories { maven { url "https://jitpack.io" } // add this line } } |
เพิ่ม dependencies
1 2 3 |
dependencies { compile 'com.github.smart-fun:XmlToJson:1.2.0' // add this line } |
2.การใช้งาน XmlToJson
1 2 3 4 5 6 7 8 |
XmlToJson xmlToJson = new XmlToJson.Builder(result).build(); JSONObject jsonObject = xmlToJson.toJson(); JSONObject admGetFacultyBudgetJsonObject = jsonObject.getJSONObject("soap:Envelope").getJSONObject("soap:Body").getJSONObject("admGetFacultyBudgetResponse"); String resultJSONResult = admGetFacultyBudgetJsonObject.getString("admGetFacultyBudgetResult"); facultybudgetMapper = new Gson().fromJson(resultJSONResult, FacultyBudgetMapper.class); |
ตัวแปร result จะเก็บ XML response ที่ได้กลับมา ซึ่งจะมีส่วน Header ต่างๆ ติดมาด้วย แปลงทั้งหมดเป็น JSONObject
1 2 3 |
XmlToJson xmlToJson = new XmlToJson.Builder(result).build(); JSONObject jsonObject = xmlToJson.toJson(); |
ดึงเอาเฉพาะ XML Result ที่จะใช้งานออกมา
1 2 |
JSONObject admGetFacultyBudgetJsonObject = jsonObject.getJSONObject("soap:Envelope").getJSONObject("soap:Body").getJSONObject("admGetFacultyBudgetResponse"); String resultJSONResult = admGetFacultyBudgetJsonObject.getString("admGetFacultyBudgetResult"); |
นำ resultJSONResult ที่ได้ไป Map โดยใช้ Gson
1 |
facultybudgetMapper = new Gson().fromJson(resultJSONResult, FacultyBudgetMapper.class); |
จบแล้วครับ เป็น code ที่ผมเขียนใน project ตัดบางส่วนมา เขียน blog เก็บไว้อ่าน (เขียนโปรแกรมอยู่ระหว่างพักก็เอางานที่เขียนมาเขียน blog อีกที ตกลงได้พักไหม? 55+)
ถ้ามีอะไรผิดพลาดก็ขออภัยไว้ ณ ที่นี้ด้วยนะครับ
XmlToJson : https://github.com/smart-fun/XmlToJson
ภาพจาก : http://www.slideshare.net/indicthreads/java-web-services-using-jaxws