2017-04-20 129 views
0
[ 
    { 
    "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://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) –

回答

0

使用傑克遜,

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

    }