我正在尝试将字符串转换为 JSONObject。这是我的代码:
JSONObject obj = new JSONObject(str);
Vehicle.feature 文件包含:
Scenario: Create a vehicle with valid json request
Given vehicle json for VehicleService
"""
"{\"vin\" : \"VIN5\", \"brand\" : \"Toyota\", \"model\" : \"Innova\", \"year\" : \"2017\", \"color\" : \"Red\", \"modelCode\" : \"1234\", \"type\" : \"M\", \"countryCode\" : \"JP\", \"isConnected\" : \"true\", \"isActive\" : \"true\"}"
"""
When performing POST on VehicleService url /add
Then VehicleService should return status code 200
VehicleStepDefs 包含:
@Given("^vehicle json for VehicleService$")
public void submitValidVehicleRequest(String vehicleJson) throws JSONException {
JSONObject obj = new JSONObject(vehicleJson);
request = given().and()
.header("Content-Type", MediaType.APPLICATION_JSON)
.accept(ContentType.JSON)
.body(obj);
request.then().log().all();
}
我的错误如下所示:
org.json.JSONException: Value {"vin" : "VIN5", "brand" : "Toyota", "model" : "Innova", "year" : "2017", "color" : "Red", "modelCode" : "1234", "type" : "M", "countryCode" : "JP", "isConnected" : "true", "isActive" : "true"} of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.examples.demo.VehicleStepDefs.submitValidVehicleRequest(VehicleStepDefs.java:43)
at ?.Given vehicle json for VehicleService(Vehicle.feature:8)
我做错了什么?
最佳答案
检查您的导入。
这是运行代码:
import org.json.JSONException;
import org.json.JSONObject;
public class TestJson {
public static void main(String[] args) {
try {
JSONObject obj = new JSONObject("{\"vin\" : \"VIN5\", \"brand\" : \"Toyota\", \"model\" : \"Innova\", \"year\" : \"2017\", \"color\" : \"Red\", \"modelCode\" : \"1234\", \"type\" : \"M\", \"countryCode\" : \"JP\", \"isConnected\" : \"true\", \"isActive\" : \"true\"}");
System.out.println(obj.get("model"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
输出:Innova
关于java - JSONException 字符串无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420945/