英文:
How to import json array into java program using JSON.ORG
问题
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
// ...
// Read and manipulate the first JSON dataset
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
// Extract the "symbols" array
JSONArray symbols = jsonObject.getJSONArray("symbols");
// ...
// Import the second JSON dataset as an array
String jsonStr = "[\n" +
" {\n" +
" \"symbol\": \"ETHBTC\",\n" +
" \"priceChange\": \"-0.00029700\"\n" +
" },\n" +
" {\n" +
" \"symbol\": \"LTCBTC\",\n" +
" \"priceChange\": \"-0.00003300\"\n" +
" }\n" +
"]";
JSONArray dataArray = new JSONArray(jsonStr);
英文:
I am learning to work with json files and I'm using the JSON-java
library from https://github.com/stleary/JSON-java
- I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
- Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
答案1
得分: 1
你已经接近成功,你只需要按照以下方式从jsonToken
中创建一个JSON数组:
顺便提一下,我认为你正在使用的JSON库是org.json
,而不是JSON.ORG
。而且你的两个JSON字符串都是无效的,如果在逗号后面没有其他JSON对象,请将其删除。
代码片段
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
控制台输出
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
英文:
You are almost there, all you have to do is to new a JSON array from jsonToken
as follows:
BTW, I think the JSON library you are using is org.json
, not JSON.ORG
. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论