英文:
How to loop through JSON objects?
问题
import org.json.JSONException;
import org.json.JSONObject;
public class StockParser {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"stocks\":{\n" +
" \"0\":{\n" +
" \"name\":\"Torn City Stock Exchange\",\n" +
" \"acronym\":\"TCSE\",\n" +
" \"director\":\"None\",\n" +
" \"current_price\":10018.747,\n" +
" \"market_cap\":0,\n" +
" \"total_shares\":0,\n" +
" \"available_shares\":0,\n" +
" \"forecast\":\"Average\",\n" +
" \"demand\":\"High\"\n" +
" },\n" +
" \"1\":{\n" +
" \"name\":\"Torn City and Shanghai Banking Corporation\",\n" +
" \"acronym\":\"TSBC\",\n" +
" \"director\":\"Mr. Gareth Davies\",\n" +
" \"current_price\":529.863,\n" +
" \"market_cap\":4300246833486,\n" +
" \"total_shares\":8115771121,\n" +
" \"available_shares\":0,\n" +
" \"forecast\":\"Average\",\n" +
" \"demand\":\"High\",\n" +
" \"benefit\":{\n" +
" \"requirement\":4000000,\n" +
" \"description\":\"Entitled to receive occasional dividends\"\n" +
" }\n" +
" },\n" +
" \"2\":{\n" +
" \"name\":\"Torn City Investment Banking\",\n" +
" \"acronym\":\"TCB\",\n" +
" \"director\":\"Mr. Paul Davies\",\n" +
" \"current_price\":502.819,\n" +
" \"market_cap\":5771083717274,\n" +
" \"total_shares\":11477457529,\n" +
" \"available_shares\":1539811799,\n" +
" \"forecast\":\"Average\",\n" +
" \"demand\":\"Average\",\n" +
" \"benefit\":{\n" +
" \"requirement\":1500000,\n" +
" \"description\":\"Entitled to receive improved interest rates\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject stocks = jsonObject.getJSONObject("stocks");
for (int i = 0; i < stocks.length(); i++) {
JSONObject stock = stocks.getJSONObject(String.valueOf(i));
String name = stock.getString("name");
String acronym = stock.getString("acronym");
int totalShares = stock.getInt("total_shares");
int availableShares = stock.getInt("available_shares");
String demand = stock.getString("demand");
System.out.println("Name: " + name);
System.out.println("Acronym: " + acronym);
System.out.println("Total Shares: " + totalShares);
System.out.println("Available Shares: " + availableShares);
System.out.println("Demand: " + demand);
System.out.println();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Above is the code to loop through the JSON data and extract the desired values using Java. Please make sure to replace jsonString
with your actual JSON data.
英文:
{
"stocks":{
"0":{
"name":"Torn City Stock Exchange",
"acronym":"TCSE",
"director":"None",
"current_price":10018.747,
"market_cap":0,
"total_shares":0,
"available_shares":0,
"forecast":"Average",
"demand":"High"
},
"1":{
"name":"Torn City and Shanghai Banking Corporation",
"acronym":"TSBC",
"director":"Mr. Gareth Davies",
"current_price":529.863,
"market_cap":4300246833486,
"total_shares":8115771121,
"available_shares":0,
"forecast":"Average",
"demand":"High",
"benefit":{
"requirement":4000000,
"description":"Entitled to receive occasional dividends"
}
},
"2":{
"name":"Torn City Investment Banking",
"acronym":"TCB",
"director":"Mr. Paul Davies",
"current_price":502.819,
"market_cap":5771083717274,
"total_shares":11477457529,
"available_shares":1539811799,
"forecast":"Average",
"demand":"Average",
"benefit":{
"requirement":1500000,
"description":"Entitled to receive improved interest rates"
}
}
}
How can I loop through all the items with key-value pairs? I want to extract name, acronym , total shares, available_shares and demand. Please help! I'm creating a android app using java and I'm stuck here.
答案1
得分: 5
以下是翻译好的内容:
IMO这不是JSON中正确表示对象列表的方式。如果可以的话,你应该将其更改为:
{
"stocks": [
{
"name": "Torn City Stock Exchange",
"acronym": "TCSE",
"director": "None",
"current_price": 10018.747,
"market_cap": 0,
"total_shares": 0,
"available_shares": 0,
"forecast": "Average",
"demand": "High"
},
{
"name": "Torn City and Shanghai Banking Corporation",
"acronym": "TSBC",
"director": "Mr. Gareth Davies",
"current_price": 529.863,
"market_cap": 4300246833486,
"total_shares": 8115771121,
"available_shares": 0,
"forecast": "Average",
"demand": "High",
"benefit": {
"requirement": 4000000,
"description": "有权获得偶尔的股息"
}
},
{
"name": "Torn City Investment Banking",
"acronym": "TCB",
"director": "Mr. Paul Davies",
"current_price": 502.819,
"market_cap": 5771083717274,
"total_shares": 11477457529,
"available_shares": 1539811799,
"forecast": "Average",
"demand": "Average",
"benefit": {
"requirement": 1500000,
"description": "有权获得改进的利率"
}
}
]
}
一个理想的方式是在Java中使用映射类,并将JSON捕获为List
private String json = "在此处放入你的JSON对象";
ObjectMapper objectMapper = new ObjectMapper();
List<MappingClass> stocks = objectMapper.readValue(jsonArray, new
TypeReference<List<MappingClass>>(){});
for (MappingClass stock : stocks) {
stock.getName();
// 其他字段
}
可以参考The Jackson Library和ObjectMapper来进行学习。
英文:
IMO this is not a proper way of having a list of objects in a JSON.
If you can, you should change this to
{
"stocks": [
{
"name": "Torn City Stock Exchange",
"acronym": "TCSE",
"director": "None",
"current_price": 10018.747,
"market_cap": 0,
"total_shares": 0,
"available_shares": 0,
"forecast": "Average",
"demand": "High"
},
{
"name": "Torn City and Shanghai Banking Corporation",
"acronym": "TSBC",
"director": "Mr. Gareth Davies",
"current_price": 529.863,
"market_cap": 4300246833486,
"total_shares": 8115771121,
"available_shares": 0,
"forecast": "Average",
"demand": "High",
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
{
"name": "Torn City Investment Banking",
"acronym": "TCB",
"director": "Mr. Paul Davies",
"current_price": 502.819,
"market_cap": 5771083717274,
"total_shares": 11477457529,
"available_shares": 1539811799,
"forecast": "Average",
"demand": "Average",
"benefit": {
"requirement": 1500000,
"description": "Entitled to receive improved interest rates"
}
}
]
}
An ideal way would be to have a mapping class in Java and capture the JSON as List<MappingClass>, then you can easily iterate.
private String json = "your json object here";
ObjectMapper objectMapper = new ObjectMapper();
List<MappingClass> stocks = objectMapper.readValue(jsonArray, new
TypeReference<List<MappingClass>>(){});
for (MappingClass stock : stocks) {
stock.getName();
// other fields
}
Try having a look over The Jackson Library and ObjectMapper for reference.
答案2
得分: 2
你可能会想要使用一个知名的 JSON 库,比如 GSON 或 JsonPullParser。GSON 可以将你的 JSON 反序列化成一个包含你需要定义的对象的 Map。所以代码会类似于一个 Map<Integer, Bank>。
你的 Bank 类会类似于这样:
public class Bank {
String acronym;
String name;
//...
Benefit benefit;
}
然后,如果你使用 GSON,你的解析代码会类似于这样:
Map<Integer, Bank> bankMap;
Gson gson = new Gson();
Type type = TypeToken.getParameterized(Map.class, Integer.class, Bank.class).getType();
// result 是包含你的 JSON 的字符串!
bankMap = gson.fromJson(result, type);
for (Bank bank : bankMap.values()) {
System.out.println("Bank name:" + bank.name);
//...
}
GSON 的文档内容丰富且写得很好。你可以在这里找到它:
https://github.com/google/gson
希望我写的内容对你有所帮助!祝你好运,并且请告诉我事情的进展情况。
英文:
You will probably want to use a well known JSON library such as GSON or JsonPullParser. GSON can deserialize your JSON into a Map that contains objects that you will have to define. So it will be something like a Map<Integer, Bank>.
Your Bank class would look something like this:
public class Bank {
String acronym;
String name;
//...
Benefit benefit;
}
and then, if you use GSON, your parsing code will look something like this:
Map<Integer,Bank> bankMap;
Gson gson = new Gson();
Type type = TypeToken.getParameterized(Map.class, Integer.class, Bank.class).getType();
//result is a String that has your JSON!
bankMap = gson.fromJson(result, type);
for (Bank bank : bankMap.values()) {
System.out.println("Bank name:" + bank.name);
//...
}
The documentation for GSON is comprehensive and well written. It can be found here:
https://github.com/google/gson
I hope what I wrote helps you! Good luck and please let me know how things went.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论