如何解析JSONObjects的JSONArray,以及JSONArray和JSONArray在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文件中的数据集,问题和解决方案。如何解析JSONObjects的JSONArray,以及JSONArray和JSONArray在JAVA里面?

+1

可能的重复[如何解析Java中的JSON](http://*.com/questions/2591098/how-to-parse-json-in-java) –

使用杰克逊,

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

数据集根据JSON结构创建

快速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其possible.This仅仅是一个例子如何阅读JSON数组和object.Using这个你可以写值回文件。

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()); 

    }