我遇到下一个错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
class org.json.simple.JSONArray cannot be cast to class
org.json.simple.JSONObject (org.json.simple.JSONArray and
org.json.simple.JSONObject are in unnamed module of loader 'app')
获取JSON的端点是:
https://www.okex.com/api/spot/v3/instruments
我已经搜索了错误,我认为问题是我正在获取JSONArray而不是JSONObject,但是我需要按键过滤,因为我需要从json中获取每个“ base_currency”。
下面是给我错误的原始代码:
private String UrlBase = "https://www.okex.com/";
private URL url;
private String inline="";
private JSONObject jobj;
private JSONObject jobj1;
private Scanner sc;
private String Symbols = "api/spot/v3/instruments";
private String Param1= "base_currency";
private JSONArray arr;
private JSONArray arr1;
private JSONParser prs;
private HttpURLConnection conn;
private ArrayList Monedas = new ArrayList();
private Conexion conc = new Conexion();
public void CargarMonedasNuevasOkex() throws IOException {
try {
url = new URL(UrlBase+Symbols);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpURLConnection)url.openConnection();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if(responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " +responsecode);
}
else{
sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+= sc.nextLine();
}
sc.close();
JSONParser parse = new JSONParser();
try {
jobj1 = (JSONObject) parse.parse(inline);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr1 = (JSONArray) jobj1.get(Param1);
System.out.println(arr.get(0));
for( int a=0; a<arr1.size(); a++ ) {
jobj1 = (JSONObject) arr1.get(a);
}
}
}
答案 0 :(得分:0)
代替
#font is an arabic font, and font_path is pointing to that location.
font = ImageFont.truetype(
font=font_path, size=size,
layout_engine=ImageFont.LAYOUT_RAQM)
h, w = font.getsize(text, direction='rtl')
offset = font.getoffset(text)
H, W = int(1.5 * h), int(1.5 * w)
imgSize = H, W
img = Image.new(mode='1', size=imgSize, color=0)
draw = ImageDraw.Draw(img)
pos = ((H-h)/2, (W-w)/2)
draw.text(pos, text, fill=255, font=font,
direction='rtl', align='center')
做
arr1 = (JSONArray) jobj1.get(Param1);
哦和
arr1=job1 ;//or jsut use the same variable
应该是
jobj1 = (JSONObject) parse.parse(inline);
然后
jobj1 = (JSONArray) parse.parse(inline);
基本上在链接中,前提是您得到的是jsonArray而不是包含数组的对象
答案 1 :(得分:0)
为您的要求根据键获取值,您可以尝试下面的代码,该代码根据JSON格式进行了修改。
set