簡體   English   中英

如何在JAVA中解析JSONObjects的JSONArray以及帶有JSONArray的JSONObjects?

[英]How to Parse JSONArray of JSONObjects, and the JSONObjects with JSONArray Inside in JAVA?

[
   {
    "dataset": "Kushman",
    "iIndex": 1964,
    "sQuestion": "The grocer has peanuts for 3.75 dollars a pound and walnuts for 2.75 dollars a pound. How many pounds of peanuts and walnuts must we mix to get 40 pounds of mixture to sell for 3.00 dollars per pound. ",
    "lEquations": [
      "(3.75*peanuts)+(2.75*walnuts)=3.0*40.0",
      "peanuts+walnuts=40.0"
    ],
    "lSolutions": [
      10.0,
      30.0
    ],
    "grammarCheck": 1,
    "templateNumber": 4
  },
  {
    "dataset": "Kushman",
    "iIndex": 2003,
    "sQuestion": "Admission tickets to a football game were 60 cents for adults and 25 cents for children. Receipts for the day showed that 280 persons attended and 140 dollars was collected. How many adults attended? How many children attended?",
    "lEquations": [
      "(60*.01*noof_adults)+(25*.01*noof_childrens)=140.0",
      "noof_adults+noof_childrens=280.0"
    ],
    "lSolutions": [
      200.0,
      80.0
    ],
    "grammarCheck": 1,
    "templateNumber": 2
  }
]

這是名為“ Kushman.json”的Json文件。 我想解析它,然后將結果保存在JSON文件中的數據集,問題和解決方案的不同文本文件中。

使用傑克遜,

ObjectMapper mapper = new ObjectMapper();
Dataset dataset = mapper.readValue(jsonString, Dataset.class);

數據集根據json結構創建

要么

Quick-json解析器,

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

我更喜歡Gson,但取決於您。

首先創建一個與您的Json數據映射的模型。

public class MyModel {
    private String dataset;
    private int iIndex;
    private String sQuestion;
    private String[] lEuqations;   
    private float[] lSolutions;
    private int grammarCheck;
    private int templateNumber;
 }

之后,您可以使用Gson映射數據。

 Gson gson = new GsonBuilder().create();
 List<MyModel> yourModel = gson.fromJson(jsonData, MyModel[].class)

而已。

不要忘記將gson添加到gradle中(如果使用gradle)。

// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

使用JsonObjects和JsonArrays是可能的,這只是一個讀取json數組和對象的示例,使用它您可以將值寫回到文件中。

JSONObject jObject = null;
    try {

    String res=FileUtils.readFileToString(new File("test.txt"));        
       jObject = new JSONObject(res);
       JSONArray j1 = jObject.JSONArray ("dataset");
       System.out.println(j1);
        j2 = j1.getJSONObject("lEquations");           
       System.out.println(j2);
    } catch (Exception e) {
        System.out.println("Exception: "+e.getMessage());

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM