使用simple-json解析json字符串

时间:2015-10-23 18:28:45

标签: java json-simple

我已经阅读了与我的问题相同的帖子但我必须遗漏一些东西。我的环境是Eclipse Mars。我的JAVA是1.7,我已经导入了json-simple。我只想解析从我的Web服务返回的json。如果我需要修改其输出,我控制Web服务。我在arg[0]中看到了如下所述的json,但是对象obj是null,当然是JSONArray数组。我知道我错过了一些基本的东西,但我很难过,有点累。

这是返回的json:

[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]

以下是使用json-simple的解析代码:

package parser;
import org.json.simple.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;

public class JsonParser 
{
    private static JSONObject _jsonInput;

    public static void main(String[] args)
    {
        //TODO

       try{
           JSONParser parser = new JSONParser();
           Object obj = JSONValue.parse(args[0]);
           JSONArray array=(JSONArray)obj;
           String name = array.get(3).toString();
           System.out.println(obj);
       }
       catch(Exception e){
           e.printStackTrace();
       }
    }

}

1 个答案:

答案 0 :(得分:2)

数组的大小与使用的索引不同

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
  String name = array.get(3).toString();