error Class cast exception in main - java

I am trying to convert json file into csv file and I am using following code for that
public File convert(File toConvert) {
// TODO Auto-generated method stub
String JsonString = "{\"value\": [{\"name\",\"kind\":\"url\":]}";
JSONParser file = new JSONParser();
Object obj = file;
JSONObject jsonfile = (JSONObject) obj; //JSONObject from map interface
String name = (String) jsonfile.get("name");
System.out.println(name);
String kind = (String) jsonfile.get("kind");
System.out.println(kind);
JSONArray url = (JSONArray) jsonfile.get("url"); //JSONArray from list interface
Iterator<String> iterator = url.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
return toConvert ;
}
and my json file has a huge data and it looks like this
{
"value":[
{
"name":"accountleadscollection","kind":"EntitySet","url":"accountleadscollection"
},{
"name":"accounts","kind":"EntitySet","url":"accounts"
},{
"name":"activitymimeattachments","kind":"EntitySet","url":"activitymimeattachments"
},{
"name":"activityparties","kind":"EntitySet","url":"activityparties"
},{
"name":"activitypointers","kind":"EntitySet","url":"activitypointers"
},{
"name":"annotations","kind":"EntitySet","url":"annotations"
},{
"name":"annualfiscalcalendars","kind":"EntitySet","url":"annualfiscalcalendars"
},{...............
whenever I am trying to execute the code i am getting this error,Exception in thread "main" java.lang.ClassCastException. Is the logic I am following is correct or can anyone provide a better code for that, and I am implementing an interface which is having this method.

Convert the String in JSONObject.
Get the Array in the JSONObject by using the method getJSONArray("arraName").
If the array consist of Object then Iterate the array and then get the object using the index using method getJSONObject(index).
Now get the value using the key.
Here is the sample code in which you can do this.
Parse JSON from the string:
public void convert() throws JSONException {
String jsonString = readFile("prop.json"); //URL of your json file
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArr = jsonObj.getJSONArray("value");
for (int j = 0; j < jsonArr.length(); j++) {
JSONObject tempJsonObj = jsonArr.getJSONObject(j);
System.out.println(tempJsonObj.get("name"));
System.out.println(tempJsonObj.get("kind"));
System.out.println(tempJsonObj.get("url"));
}
}
Read JSON file:
public String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Related

Parse JSON having both Escape & Unescape characters in JAVA using Jayway

I receive the below json as an input to my program:
{
"shopping": {
"cart": {
"items": [{
"iturl" : "https://www.google.com/",
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
We are using jayway jsonpath to parse this data and do some processing and return the final value as a string.
when we parse it with the default jsonpath configuration, I get the iturl modified as "https:\/\/www.google.com\/"
Tried changing the JSONProvider to JacksonJsonProvider (by referring Jsonpath with Jackson or Gson) and the issue with the url is solved but, the value of itdesc is now coming to new line (due to \n) making it an invalid json.
I cannot specifically handle for each field as the incoming data will be dynamic.
Is there any proper way to parse this kind of JSON in java. Thanks in advance for your help
Try adding one more escaping level before parsing the string, the string parser's gonna give you "\n" for "\\n".
For example, parsing with Jackson ObjectMapper.
objectMapper.readValue(jsonString.replace("\\", "\\\\"), Any.class);
{
"shopping": { <-- JSONObject
"cart": { <-- JSONObject
"items": [{ <-- JSONArray
"iturl" : "https://www.google.com/", <-- JSONObject inside JSONAray
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
if this data json come from http connection.
this json must be a string format fisrt,
and try using org.json.simple
so do like this :
private void readData() {
String Body = (response json string from connection);
JSONParser parse = new JSONParser();
String iturl = null;
String itdesc = null;
try {
JSONObject shopping = (JSONObject) parse.parse(Body);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
}catch ( ParseException e) {
e.printStackTrace();
}
}
if this come from file.json combine with reader :
private static final File jsonData = new File(file.json);
private void callData() {
String iturl = null;
String itdesc = null;
try {
Reader reader = new FileReader(marketList);
JSONParser parse = new JSONParser();
JSONObject shopping = (JSONObject) parse.parse(reader);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}

How to parse json response, when the response does not contain header information

I am trying to parse a json response so that i can get elements out of an object, getting the following error A JSONObject text must begin with '{' at 1 [character 2 line 1]
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jsonObj = new JSONObject(json);
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
String aId = jsonObj.getString("id");
uId = aId;
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Here is json response using postman you will notice there is no header
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1",
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2",
}
]
Like the comment above mentioned, that is a JSON array so it needs to be parsed as a JSON array and not a JSON object. Just use the JSONArray equivalent provided in the library you are using.
On another note, with the JSON response above, parsing this as a JSON array would fail since the format is incorrect. Notice the comma at the end of every last keyvalue in each object. That would cause the parser to fail when attempting to parse that as a JSON array. If that was your mistake when you were writing the snippet here then ignore this paragraph. Else if that was the actual JSON response then I guess you need to make a new question... over at the Postman forum.
There are several ideas for this case.
Here is mine.
With a json simple library[link].
You can simply change your library to a json simple library which has a parser class for a json string
then use an instanceof method for detection before processing a json object.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONParser parser = new JSONParser();
Object whichone = parser.parse(json);
if(whichone instanceof JSONObject)
{
JSONObject jsonObj = (JSONObject)whichone;
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
if(jsonObj.containsKey("id"))
uId = (String)jsonObj.get("id");
}
else if(whichone instanceof JSONArray)
{
JSONArray jsonArr = (JSONArray)whichone;
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.size(); i++)
{
jsonObj = (JSONObject) jsonArr.get(i);
if(jsonObj.containsKey("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
else if(whichone instanceof String)
{
System.out.println("1?????" + whichone.toString());
}
else
{
System.out.println("2?????" + whichone.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Detect the object type from a json excetpion.
You can catch it whether some string is a json object or json array during exception handling.
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} catch (org.json.JSONException e) {
//e.printStackTrace();
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
With a java work.
You can find it whether it's a json object or array after parsing a first character.
(I think it will work...)
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
boolean isJobj = json.charAt(0) == '[';
if(!isJobj) {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} else {
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
Have a good day..
First, Your json format is wrong. The correct json format would be:
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1"
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2"
}
]
Now,
Your Response is JSON Array. So first assign parsed object into JSON Array as JSONArray array = (JSONArray) obj;
this JSON Array consists of two JSON Object so traverse the array, get each JSON Object and print/return key/value pair whatever you want.
A sample code is given below:(see the logic)
public static void parseJsonResponse(String json)
throws JsonParseException, JsonMappingException, IOException, ParseException {
String aId ="";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONArray array = (JSONArray) obj;
for(int i=0;i<array.size();i++)
{
JSONObject jsonObject = (JSONObject) array.get(i);
aId = (String) jsonObject.get("id");
System.out.println(aId);
}
}
Note: I have used json-simple java library here.

JSON stored as string. Cant seem to parse it - Java

This is what I have to read text in JSON format from a website. But i get the error
Java.lang.ClassCastException: org.json.simple.JSONObject cannot be
cast to org.json.simple.JSONArray
This is driving me nuts. Can anyone help? I also need to check this string for all instances of "Username" and run something for each of them.
public class CommandCheck implements CommandExecutor {
private String username;
private static String host = "example.com";
private URL url;
private String apiKey = main.getNode("API-KEY");
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg3) {
try {
this.url = new URL(CommandCheck.host);
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("x-api-key", this.apiKey);
}
conn.addRequestProperty("User-Agent", main.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
sender.sendMessage(response); //Im just dumping the raw String for the person running the command to see Debug mostly
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
sender.sendMessage("The Array appears to be empty");
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
username = (String) latestUpdate.get("Username");
sender.sendMessage("whitelist add" + username);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
sender.sendMessage("I think there is an API key issue");
} else {
sender.sendMessage("Problem of unknown orign");
}
return false;
}
}
Try changing the following line:
final JSONArray array = (JSONArray) JSONValue.parse(response);
to:
final JSONObject jsObj = (JSONObject) JSONValue.parse(response);
Can you provide the JSON String you are trying to parse? I.e. the value of response?
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes") ;
org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray means that you are trying to convert the json object into the json array. if your response in the json object as a response then you first need it to convert in the Json object.
after converting you can get the the Json array from the json object using the get("key-name")
JSONObject resObj = new JSONObject(responseString);
JSONArray resArray = resObj.getJSONArray("Username");
for (int i=0; i<resArray.length(); i++)
String resultString = resArray.getString(i);
it gives you all usersname.
i think this code helps you to solve your problem.

Read Multiple Objects JSON with Java

I need to read a JSON file in Java with the following structure:
{"id_user":"10","level":"medium","text":"hello 10"}
{"id_user":"20","level":"medium","text":"hello 20"}
{"id_user":"30","level":"medium","text":"hello 30"}
Thanks!.
[POST-EDITED]
I have this code but only read the first JSON Object, I need read the three objects one by one.
private void loadJSONFile(){
FileReader fileReader = new FileReader(pathFile);
try (JsonReader jsonReader = new JsonReader(fileReader)) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("filter_level")) {
System.out.println(jsonReader.nextString());
} else if (name.equals("text")) {
System.out.println("text: " + jsonReader.nextString());
} else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
jsonReader.close();
}
}
thanks!
This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrary sequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have formatted your input:
InputStream is = /* whatever */
Reader r = new InputStreamReader(is, "UTF-8");
Gson gson = new GsonBuilder().create();
JsonStreamParser p = new JsonStreamParser(r);
while (p.hasNext()) {
JsonElement e = p.next();
if (e.isJsonObject()) {
Map m = gson.fromJson(e, Map.class);
/* do something useful with JSON object .. */
}
/* handle other JSON data structures */
}
I know it has been almost one year for this post :) but i am actually reposing again as an answer because i had this problem same as you Yuan
I have this text.txt file - I know this is not a valid Json array - but if you look, you will see that each line of this file is a Json object in its case alone.
{"Sensor_ID":"874233","Date":"Apr 29,2016 08:49:58 Info Log1"}
{"Sensor_ID":"34234","Date":"Apr 29,2016 08:49:58 Info Log12"}
{"Sensor_ID":"56785","Date":"Apr 29,2016 08:49:58 Info Log13"}
{"Sensor_ID":"235657","Date":"Apr 29,2016 08:49:58 Info Log14"}
{"Sensor_ID":"568678","Date":"Apr 29,2016 08:49:58 Info Log15"}
Now I want to read each line of the above and parse the names "Sensor_ID" and "Date" into Json format. After long search, I have the following:
Try it and look on the console to see the result. I hope it helps.
package reading_file;
import java.io.*;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class file_read {
public static void main(String [] args) {
ArrayList<JSONObject> json=new ArrayList<JSONObject>();
JSONObject obj;
// The name of the file to open.
String fileName = "C:\\Users\\aawad\\workspace\\kura_juno\\data_logger\\log\\Apr_28_2016\\test.txt ";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
obj = (JSONObject) new JSONParser().parse(line);
json.add(obj);
System.out.println((String)obj.get("Sensor_ID")+":"+
(String)obj.get("Date"));
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I think what you mean is your Json strings are stored in a text file and you need to read them in to a Json objects. If that's the case use BufferedReader or Scanner to read the file line by line and parse each line to a Json object using json-simple
JsonReader is use to Read One Json Object. Use Scanner or BufferedReader to Read File Line By Line as String and then Parse it to a Json Object.Here is an Example
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class JSONExample{
public static void main(String x[]){
String FileName="C:\\Users\\Prasad\\Desktop\\JSONExample.txt";
try {
ArrayList<JSONObject> jsons=ReadJSON(new File(FileName),"UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public static synchronized ArrayList<JSONObject> ReadJSON(File MyFile,String Encoding) throws FileNotFoundException, ParseException {
Scanner scn=new Scanner(MyFile,Encoding);
ArrayList<JSONObject> json=new ArrayList<JSONObject>();
//Reading and Parsing Strings to Json
while(scn.hasNext()){
JSONObject obj= (JSONObject) new JSONParser().parse(scn.nextLine());
json.add(obj);
}
//Here Printing Json Objects
for(JSONObject obj : json){
System.out.println((String)obj.get("id_user")+" : "+(String)obj.get("level")+" : "+(String)obj.get("text"));
}
return json;
}
}
include following maven dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
then write your code as below:
public class HistoricalData {
private static final String PATH = "<PATH>";
public static void main(String[] args) throws FileNotFoundException,
ParseException {
Scanner scanner = new Scanner(new File(PATH + "/Sample.txt"));
List<JSONObject> jsonArray = new ArrayList<JSONObject>();
while (scanner.hasNext()) {
JSONObject obj = (JSONObject) new JSONParser().parse(scanner.nextLine());
jsonArray.add(obj);
}
}
}
keep the data inside [ ] like
[{"id_user":"10","level":"medium","text":"hello 10"}
{"id_user":"20","level":"medium","text":"hello 20"}
{"id_user":"30","level":"medium","text":"hello 30"}]
inside the file
so that it becomes a list then you can use JSONArray . the way I wrote is as follows
public class JSONReadFromFile {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("\\D:\\JSON\\file3.txt"));
JSONArray jsonArray = (JSONArray) obj;
int length = jsonArray.size();
LinkedList author = new LinkedList();
for (int i =0; i< length; i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Set s = jsonObject.entrySet();
Iterator iter = s.iterator();
HashMap hm = new HashMap();
while(iter.hasNext()){
Map.Entry me = (Map.Entry) iter.next();
hm.put(me.getKey(), me.getValue());
}
author.add(hm);
}
for(int i=0;i<author.size();i++){
HashMap hm = (HashMap) author.get(i);
Set s = hm.entrySet();
Iterator iter = s.iterator();
while(iter.hasNext()){
Map.Entry me = (Map.Entry) iter.next();
System.out.println(me.getKey() + "---" + me.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output I get is
text---hello 10
id_user---10
level---medium
text---hello 20
id_user---20
level---medium
text---hello 30
id_user---30
level---medium
I know two option for read JSON.
JSON Simple its good for small JSON results.
But GSON is very usefull for big json results. Because you can set Object form in GSON.
Firs one json.jar
Usage :
String st = ""; // your json object to string
JSONObject newJson = null;
try {
newJson = new JSONObject(st);
newJson.getJSONObject("key");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Second One gson.jar
Usage:
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class);
The proper way to work through this JSON file is:
"users": [
{
"id_user": "10",
"level": "medium",
"text": "hello 10"
},
{
"id_user": "20",
"level": "medium",
"text": "hello 20"
},
{
"id_user": "30",
"level": "medium",
"text": "hello 30"
}
]
Try using XStream if you are using a standalone application. It parses JSON into objects in a blink of an eye.
Using gson to read multiple objects from stream.
With gson-2.8.2, I had to call this: reader.setLenient(true);
JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.setLenient(true);
while ((is.available() > 0))
{
reader.beginObject();
while (reader.hasNext()) {
System.out.println("message: "+reader.nextName()+"="+reader.nextString());
}
System.out.println("=== End message ===");
reader.endObject();
This was suggested explicitly by the stack trace, when I did it, the code worked perfectly:
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 3481 path $
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1409)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:542)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:379)
...
I used below code and its working fine.
public static void main(String[] args)
throws IOException, JSchException, SftpException, InterruptedException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("c:\\netapp1.txt"));
Map<Object, Object> shareList = new HashMap<Object, Object>();
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("dataLevels"); // it should be any array name
Iterator<Object> iterator = array.iterator();
while (iterator.hasNext())
{
Object it = iterator.next();
JSONObject data = (JSONObject) it;
shareList.put(data.get("name"), data.get("type"));
}
Iterator it = shareList.entrySet().iterator();
while (it.hasNext())
{
Map.Entry value = (Map.Entry) it.next();
System.out.println("Name: " + value.getKey() + " and type: " + value.getValue());
}
}
JSON:
{
"version": 1,
"dataLevels":
[
{
"name": "test1",
"externId": "test1",
"type": "test1"
},
{
"name": "test2",
"externId": "test2",
"type": "test2"
},
{
"name": "test3",
"externId": "test3",
"type": "test3"
}
]
}
My data format is :
"array": [
{
"id": "1",
"name": "peter",
"text": "hie peter"
},
{
"id": "5",
"name": "rina",
"text": "hey rina"
},
{
"id": "12",
"name": "parx",
"text": "hey bro"
}
]
I tried this one and it works :
Object obj = parser.parse(new FileReader("/home/hp2/json.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("array"); // it should be any array name
Iterator<Object> iterator = array.iterator();
while (iterator.hasNext()) {
System.out.println("if iterator have next element " + iterator.next());
}

How to get the data from the Json file in the following Code

I am new to json so please help me to get solve this
propertyAlerts: [
{
alertDomain: "oiq.core.alert.PropertyAlert",
alertType: "HERITAGE_DETECTED",
oiqCreatedDate: "2013-11-04 03:06:26"
}]
By using java, I want to get the following data
OUTPUT:
alertDomain: "oiq.core.alert.PropertyAlert"
alertType: "HERITAGE_DETECTED"
oiqCreatedDate: "2013-11-04 03:06:26"
The following is used by me
public void checklicense(String filename) throws Exception
{
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./output_profiles/"+filename));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = obj.getJSONArray("propertyalert");
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String alertDomain = childJSONObject.getString("alertDomain");
}
Can any one help me to solve this problem
This tutorial explains the basics of JSON parsing.
I would recommend you to read the entire post as it is something that you will do almost daily in Android development.
public static void checklicense(String filename)
{
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
System.out.println(obj.getClass());
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = (JSONArray) jsonObject.get("propertyAlerts");
Iterator iterator = jsonMainArr.iterator();
while(iterator.hasNext()) {
jsonObject =(JSONObject) iterator.next();
String alertDomain = (String) jsonObject.get("alertDomain");
String alertType = (String) jsonObject.get("alertType");
System.out.println("alertDomain " + alertDomain + ", alertType " + alertType );
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(EosClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The above code produces the required output for a valid json input
{
"propertyAlerts": [
{
"alertDomain": "oiq.core.alert.PropertyAlert",
"alertType": "HERITAGE_DETECTED",
"oiqCreatedDate": "2013-11-04 03:06:26"
}
]
}

Categories