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依賴

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
</dependency>
<dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
</dependency>

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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章