Gson Object與json轉換 巢狀物件
阿新 • • 發佈:2018-12-26
解決問題
正確:
{
"data":
{accesstoken : "odA5niNeOhhi1cIK0eOGhrxCB7ClG9R4gl%2Fa2%2FNcOaJ42tWayXKZZZBgIPsh1tRLshlxWyXlEyY...",
expirein :"2017-11-27 14:49:23"
},
"flag":1,
"success":1,
"expired":0
}
錯誤:
{
flag:1,
expired :0,
success : 0,
err :{
code :"xxx",
Msg :"密碼錯誤"
}
}
import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.lenovo.pcsd.bp.businesspartner.bean.UserModel; import okhttp3.*; import java.util.HashMap; import java.util.Map; public class HttpUtils { public static Map post(String url,Object obj){ //建立連線客戶端 OkHttpClient client = new OkHttpClient(); //使用Gson 新增 依賴 compile 'com.google.code.gson:gson:2.8.1' Gson gson = new Gson(); //使用Gson將物件轉換為json字串 String json = gson.toJson(obj); //MediaType 設定Content-Type 標頭中包含的媒體型別值 RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8") , json); Request request = new Request.Builder() .url(url)//請求的url .post(requestBody) .build(); Call call = client.newCall(request); Response response;//執行 { try { response = call.execute(); if (response.isSuccessful()) { String result=response.body().string(); Map<String,String> resultMap=new HashMap<String, String>(); if(JSONObject.parseObject(result).get("success").equals(1)){ JSONObject object = JSONObject.parseObject(result).getJSONObject("data"); String accesstoken= (String) object.get("accesstoken"); String expirein= (String) object.get("expirein"); resultMap.put("success","1"); resultMap.put("accesstoken",accesstoken); resultMap.put("expirein",expirein); }else { String errCode = (String) JSONObject.parseObject(result).getJSONObject("err").get("code"); String errMsg = (String) JSONObject.parseObject(result).getJSONObject("err").get("msg"); resultMap.put("success","0"); resultMap.put("errCode",errCode); resultMap.put("errMsg",errMsg); } return resultMap; } } catch (Exception e) { e.printStackTrace(); } } return null; } }