[英]Java string convert to JSON object for http POST
我正在嘗試重新創建使用WebAPI的http Post請求。 我最初是用C#創建的,並且可以使用。 但是類似的Java似乎給了我一點...
我的輸入字符串包含webapi期望的參數。
String input = "{" +
"\"UserID\":xxx," +
"\"UserPsw\":\"yyy," +
"\"ApiFunction\":zzz," +
"\"DppName\":aaaa," +
"\"DppVersion\":Latest, " +
"\"ClearData\"ftfdgfdgfdg fdgfdgfd 4354534," +
"\"ResultType\":JSON \"}";
現在,我從以下位置下載了JSON簡單的jar文件:-https: //code.google.com/archive/p/json-simple/downloads
並將其導入到Java項目的我的庫文件夾中。
然后對於我的main.java類,導入了以下內容:
import org.json.simple.JSONObject;
目的是將我的“輸入”字符串轉換為JSON onbject,例如:
JSONObject jsonObject = new JSONObject(input);
但我收到一條錯誤消息:
cannot find symbol
symbol: constructor JSONObject(java.lang.String)
location: class org.json.simple.JSONObject
我究竟做錯了什么?
我想將其轉換為JSON對象的原因是因為我的webapi期望字符串使用某種格式...
{"UserID":xx,"UserPsw":yyy,"ApiFunction":zzz,"DppName":aaaa,"DppVersion":Latest, "ClearData":ftfdgfdgfdg fdgfdgfd 4354534,"ResultType":JSON "}
但是我的java字符串輸入的格式為:-
{"UserID":"xx","UserPsw":"yyy","ApiFunction":"zzz","DppName":"aaaa","DppVersion":"Latest", "ClearData":"ftfdgfdgfdg fdgfdgf 4354534","ResultType":"JSON"}
這與C#將其作為類對象發送時僅在屬性名稱(而不是值)之間加引號的方式不同。
根據文檔
http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/JSONObject.html
沒有接受String
作為參數的構造函數。 您可能會考慮將其轉換為Map
,以使其更清晰,更不易出錯。
HashMap<String,String> newMap = new HashMap<>();
newMap.put("UserID","xxx");
//... the rest of your attributes
JSONObject jsonObject = new JSONObject(newMap);
根據“ Mappan”的建議,您也可以使用JSONParser:
try {
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.