在接口测试中我们需要对获取到的json字符串做一些处理,从json字符串中获取到指定的字段来进行校验,下面来总结一下对json字符串的一些处理。
JSONArray与JSONObject简介 数据表示形式JSONObject的数据是用 { } 来表示的,
例如: { “id” : “123”, “name” : “hello”, “title” : “work”, “content” : null }
而JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , …… , { } ] 来表示
例如: [ { “id” : “123”, “name” : “hello”, “title” : “work” } , { “content” : null} ] ;
表示了包含2个JSONObject的JSONArray。
可以看到一个很明显的区别,一个最外面用的是 { } ,一个最外面用的是 [ ] ;
第一种json字符串处理
String jsonstr="{“id”:“66”,“name”:“helloword”,“age”:“18”}";
GetJsonValue gjv=new GetJsonValue();
gjv.getJsonValue(jsonstr,“name”);
gjv.getJsonValue(jsonstr,“id”);
/**
Description:根据json字符串和key值得到key对应的value值,格式如下:{key1:value,key2:value2}
@param jsonstr
@param key
*/
public String getJsonValue(String jsonstr,String key){
String valuestr="";
if(jsonstr==null || jsonstr.trim().length()==0){
return null;
}
try {
JSONObject obj=new JSONObject(jsonstr);
valuestr=obj.getString(key);
System.out.println(“valuestr=”+valuestr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return valuestr;
}
第二种json字符串处理
String str="{“languages”: [{ “langIsoCode”: “en_US”, “langActiveFlag”: true, “langName”: “United States/English” }], “currencies”: [{ “currencyIsoCode”: “USD”, “currencyActiveFlag”: true, “currencyBaseFlag”: false }]}";
gjv.getJsonArrayValue(str, “languages”,0,“langIsoCode”);
/**
*/
public String getJsonArrayValue(String jsonstr,String key,int index,String key1){
JSONArray jsonArray=new JSONArray();
String getStr="";
if(jsonstr==null || jsonstr.trim().length()==0){
return null;
}
try {
JSONObject obj=new JSONObject(jsonstr);
jsonArray=obj.getJSONArray(key);
int arraySize=jsonArray.length();
System.out.println(“arraySize=”+arraySize);
JSONObject jsonObject=jsonArray.getJSONObject(index);
getStr=jsonObject.getString(key1);
System.out.println(“getStr=”+getStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getStr;
}
第三种json字符串处理
String str2="[{ “unitId”: “ieweb” },{ “unitId”: “PUBLIC_IE” },{ “unitId”: “Ireland” },{ “unitId”: “UKI” },{ “unitId”: “WE” },{ “unitId”: “EMEA” },{ “unitId”: “PUBLIC_GLOBAL_B2C_UNIT” }]";
gjv.getJsonArrayValue(str2, 1, “unitId”);
/**
*/
public String getJsonArrayValue(String jsonstr,int index,String key){
String jsonValue="";
if(jsonstr==null || jsonstr.trim().length()==0){
return null;
}
try {
JSONArray jsonArr=new JSONArray(jsonstr);
System.out.println(“jsonArr size=”+jsonArr.length());
JSONObject jsonObj=jsonArr.getJSONObject(index);
jsonValue=jsonObj.getString(key);
System.out.println(jsonValue);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonValue;
}