当我尝试使用// first marshal your complex data structure
complexData := someComplexStruct{...}
b, _ := json.Marshal(complexData)
// then assign the returned json string to one key of your choice
data := map[string]interface{}{"key":string(b)}
间谍JSONObject
时,我觉得有些不对劲。这是来自单元测试方法的代码:
Mockito
以下是方法JSONObject json = new JSONObject();
json.put("token","value");
JSONObject spyJson = Mockito.spy(JSONObject.class);
PowerMockito.whenNew(JSONObject.class).withAnyArguments().thenReturn(spyJson);
service.getToken(json.toString());
的开始:
getToken()
在我的build.gradle中,我添加了:
public LoginResponseData getToken(String response) throws JSONException {
JSONObject resJson = new JSONObject(response); //resJson = {} here
//do stuff
}
答案 0 :(得分:0)
我认为你写的代码很好。确保您使用的库( java-json.jar )是正确的。
我在我自定义创建的Class JSONTest 下面编写了相同的代码,它运行正常。
我已经下载了java-jason.jar表单here,其中包含您在评论“ org.json.JSONObject ”中提到的相同包(您可以尝试使用将链接的jar放入您的项目中)。
以下是工作代码段:
import org.json.JSONException;
import org.json.JSONObject;
public class JSONTest {
public static void main(String[] args) throws JSONException {
JSONObject json = new JSONObject();
json.put("key", "value");
String jsonString = json.toString();
String key = new JSONObject(jsonString).getString("key");
System.out.println(key);
}
}
<强>输出:强>
value
答案 1 :(得分:0)
实际上,问题在于:
JSONObject spyJson = Mockito.spy(JSONObject.class);
正如@Sotirios Delimanolis所提到的,我应该监视json
,而不是JSONObject
类。在这里,我总是得到默认的{}
值,无论如何,因为spyJson
是JSONObject
类的新间谍,并且它不知道以前添加的token
键。将其更改为:
JSONObject spyJson = Mockito.spy(json);
它按预期工作。