我正在学习Java和JSON解析。
我有这段代码:
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJsonFaculties
{
public static void main(String[] args) {
String url = "https://somesite/";
try {
String facultiesJson = IOUtils.toString(new URL(url), "default");
JSONObject facultiesJsonObject = (JSONObject) JSONValue.parseWithException(facultiesJson);
// get id.
JSONArray facultiesArrayId = (JSONArray) facultiesJsonObject.get("Id");
// get name.
JSONArray facultiesArrayName = (JSONArray) facultiesJsonObject.get("Name");
// get get shortname.
JSONArray facultiesArrayShortname = (JSONArray) facultiesJsonObject.get("ShortName");
// output.
System.out.print(facultiesArrayId + " ");
System.out.print(facultiesArrayName + " ");
System.out.print(facultiesArrayShortname);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
但是这会返回XML而不是JSON。
来自终端的类似内容:
$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" https://univeris.susu.ru/services/mobile/Faculties
实际上返回JSON字符串。
那么如何更改此代码中的内容类型?谢谢!