java读取json文件并转化为JSONObject,并修改json的value值,问题总结

public boolean putPipelineConfig(String pipelineId) {

    boolean result = false;
    try {
        Header[] headers = null;
        String input = FileUtils.readFileToString(new File("src/test/resources/pipelineConfig.json"), "UTF-8");     //需要maven依赖
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(input);     //需要maven依赖
        //System.out.println(jsonObject);

        jsonObject.put("id", pipelineId);    //修改默认json文件里的value
        //System.out.println(jsonObject);

        String url = Constants.PIPELINE_API;
        if (!url.endsWith(pipelineId))
            url += pipelineId;
        HttpResponse response = HttpRequest.Put(TestBase.hostPort + url,
                TestBase.cookie,
                headers,
                jsonObject.toString());
        int responseCode = response.getStatusLine().getStatusCode();
        result = responseCode == 204 ? true : false;

    } catch (Exception e) {
        System.out.println(methodName + ": failed with Exception as:" + e);
        e.printStackTrace();
        Assert.fail("failed with Exception as:" + e);

    }
    return result;
}

1.需要maven依赖


            commons-io
            commons-io
            2.4


            net.sf.json-lib
            json-lib
            2.4
            jdk15

2.import导包:import net.sf.json.JSONObject;

但是,import net.sf.json.JSONObject;与import org.json.simple.JSONObject;同时出现会报错:

'org.json.simple.JSONObject' is already defined in a single-type import

解决方法:

不导入net.sf.json.JSONObject包,在使用时:(依赖依然需要)

net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(input);

你可能感兴趣的:(编程语言)