如何在JAVA中解析JSONArray的JSONArray和带JSONArray Inside的JSONObjects?

时间:2017-04-20 09:50:22

标签: java json

[
   {
    "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文件中所示。

3 个答案:

答案 0 :(得分:0)

使用杰克逊,

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

根据json结构创建数据集

Quick-json Parser,

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

答案 1 :(得分:0)

我更喜欢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'

答案 2 :(得分: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());

    }