解决 java.lang.RuntimeException: Method i in android.util.Log not mocked. See http://g.co/androidstudio/not-mocked for details.
1. 原因
Android SDK 中测试一个 Json 不会消耗哪些本不必要的资源.
2. 解决
添加包
testImplementation 'org.json:json:20201115'
自定义一个 JsonUtils 文件
package com.ykenan.alipay.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public Map<String, Object> parse(String jsonStr) {
Map<String, Object> result = null;
if (null != jsonStr) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
result = parseJSONObject(jsonObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // if (null != jsonStr)
return result;
}
private Object parseValue(Object inputObject) throws JSONException {
Object outputObject = null;
if (null != inputObject) {
if (inputObject instanceof JSONArray) {
outputObject = parseJSONArray((JSONArray) inputObject);
} else if (inputObject instanceof JSONObject) {
outputObject = parseJSONObject((JSONObject) inputObject);
} else if (inputObject instanceof String || inputObject instanceof Boolean || inputObject instanceof Integer) {
outputObject = inputObject;
}
}
return outputObject;
}
private List<Object> parseJSONArray(JSONArray jsonArray) throws JSONException {
List<Object> valueList = null;
if (null != jsonArray) {
valueList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Object itemObject = jsonArray.get(i);
if (null != itemObject) {
valueList.add(parseValue(itemObject));
}
} // for (int i = 0; i < jsonArray.length(); i++)
} // if (null != valueStr)
return valueList;
}
private Map<String, Object> parseJSONObject(JSONObject jsonObject) throws JSONException {
Map<String, Object> valueObject = null;
if (null != jsonObject) {
valueObject = new HashMap<>();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String keyStr = keys.next();
Object itemObject = jsonObject.opt(keyStr);
if (null != itemObject) {
valueObject.put(keyStr, parseValue(itemObject));
} // if (null != itemValueStr)
} // while (keyStr.hasNext())
} // if (null != valueStr)
return valueObject;
}
}
测试
JsonUtils jsonUtils = new JsonUtils();
System.out.println(jsonUtils.parse(jsonData).get("name"));