如何循环遍历JSON对象?

huangapple go评论81阅读模式
英文:

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.

英文:
{
&quot;stocks&quot;:{
&quot;0&quot;:{
&quot;name&quot;:&quot;Torn City Stock Exchange&quot;,
&quot;acronym&quot;:&quot;TCSE&quot;,
&quot;director&quot;:&quot;None&quot;,
&quot;current_price&quot;:10018.747,
&quot;market_cap&quot;:0,
&quot;total_shares&quot;:0,
&quot;available_shares&quot;:0,
&quot;forecast&quot;:&quot;Average&quot;,
&quot;demand&quot;:&quot;High&quot;
},
&quot;1&quot;:{
&quot;name&quot;:&quot;Torn City and Shanghai Banking Corporation&quot;,
&quot;acronym&quot;:&quot;TSBC&quot;,
&quot;director&quot;:&quot;Mr. Gareth Davies&quot;,
&quot;current_price&quot;:529.863,
&quot;market_cap&quot;:4300246833486,
&quot;total_shares&quot;:8115771121,
&quot;available_shares&quot;:0,
&quot;forecast&quot;:&quot;Average&quot;,
&quot;demand&quot;:&quot;High&quot;,
&quot;benefit&quot;:{
&quot;requirement&quot;:4000000,
&quot;description&quot;:&quot;Entitled to receive occasional dividends&quot;
}
},
&quot;2&quot;:{
&quot;name&quot;:&quot;Torn City Investment Banking&quot;,
&quot;acronym&quot;:&quot;TCB&quot;,
&quot;director&quot;:&quot;Mr. Paul Davies&quot;,
&quot;current_price&quot;:502.819,
&quot;market_cap&quot;:5771083717274,
&quot;total_shares&quot;:11477457529,
&quot;available_shares&quot;:1539811799,
&quot;forecast&quot;:&quot;Average&quot;,
&quot;demand&quot;:&quot;Average&quot;,
&quot;benefit&quot;:{
&quot;requirement&quot;:1500000,
&quot;description&quot;:&quot;Entitled to receive improved interest rates&quot;
}
}
}

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

{
&quot;stocks&quot;: [
{
&quot;name&quot;: &quot;Torn City Stock Exchange&quot;,
&quot;acronym&quot;: &quot;TCSE&quot;,
&quot;director&quot;: &quot;None&quot;,
&quot;current_price&quot;: 10018.747,
&quot;market_cap&quot;: 0,
&quot;total_shares&quot;: 0,
&quot;available_shares&quot;: 0,
&quot;forecast&quot;: &quot;Average&quot;,
&quot;demand&quot;: &quot;High&quot;
},
{
&quot;name&quot;: &quot;Torn City and Shanghai Banking Corporation&quot;,
&quot;acronym&quot;: &quot;TSBC&quot;,
&quot;director&quot;: &quot;Mr. Gareth Davies&quot;,
&quot;current_price&quot;: 529.863,
&quot;market_cap&quot;: 4300246833486,
&quot;total_shares&quot;: 8115771121,
&quot;available_shares&quot;: 0,
&quot;forecast&quot;: &quot;Average&quot;,
&quot;demand&quot;: &quot;High&quot;,
&quot;benefit&quot;: {
&quot;requirement&quot;: 4000000,
&quot;description&quot;: &quot;Entitled to receive occasional dividends&quot;
}
},
{
&quot;name&quot;: &quot;Torn City Investment Banking&quot;,
&quot;acronym&quot;: &quot;TCB&quot;,
&quot;director&quot;: &quot;Mr. Paul Davies&quot;,
&quot;current_price&quot;: 502.819,
&quot;market_cap&quot;: 5771083717274,
&quot;total_shares&quot;: 11477457529,
&quot;available_shares&quot;: 1539811799,
&quot;forecast&quot;: &quot;Average&quot;,
&quot;demand&quot;: &quot;Average&quot;,
&quot;benefit&quot;: {
&quot;requirement&quot;: 1500000,
&quot;description&quot;: &quot;Entitled to receive improved interest rates&quot;
}
}
]
}

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 = &quot;your json object here&quot;;
ObjectMapper objectMapper = new ObjectMapper();
List&lt;MappingClass&gt; stocks = objectMapper.readValue(jsonArray, new 
TypeReference&lt;List&lt;MappingClass&gt;&gt;(){});
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&lt;Integer, Bank&gt; 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&lt;Integer,Bank&gt; 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(&quot;Bank name:&quot; + 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.

huangapple
  • 本文由 发表于 2020年8月21日 20:14:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63522746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定