MikeReynolds
MikeReynolds

Reputation: 325

How to parse JSON string using json-simple?

I've read the posts that appeared to be the same as my question, but I might be missing something.

My environment is Eclipse Mars. My Java is 1.7, and I have imported json-simple.

I simply wish to parse the JSON, that is returned from my web service. I control the web service if I need to modify its output.

I see the JSON in arg[0] as noted below, however the object obj is null, as of course is the JSON array array.

I know that I am missing something basic, but I am stumped and a bit tired.

Here is the returned 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"}]

Here is the parse code using 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();
       }
    }
    
}

Upvotes: 1

Views: 3321

Answers (1)

Roman C
Roman C

Reputation: 1

The size of the array different than the index used

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

Upvotes: 2

Related Questions