JSON to Java gives errors - java

I'm trying to parse this following JSON string to java.
{"Stdout":"Hello World\nThis is Sara","Stderr":"exit status 124"}
This string is dynamic and the content can be different as in,
{"Stdout":"Hello World\nThis is Sara","Stderr":""}
or
{"Stdout":"","Stderr":"exit status 124"}
I'm using the following tutorial and instead of the file I'm adding my String in it.
So I created this code to simply print what "Stdout" and "Stderr" have to say:
public void parsed(String str) {
JSONParser parser=new JSONParser();
try {
Object obj = parser.parse(str);
JSONObject jsonObject = (JSONObject) obj;
JSONArray out = (JSONArray) jsonObject.get("Stdout");
Iterator<String> iterator = out.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// loop array
JSONArray err = (JSONArray) jsonObject.get("Stderr");
Iterator<String> iterator2 = err.iterator();
while (iterator2.hasNext()) {
System.out.println(iterator2.next());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
I'm getting the following result. And I have tried each and every possible solution that I found on Stack Overflow and other sites.
java.lang.String cannot be cast to org.json.simple.JSONArray

The conversions of stdout and stderr are wrong. They're both a String instead of a JSONArray. Try this:
Change: JSONArray out = (JSONArray) jsonObject.get("Stdout");
To: String stdout= (String) jsonObject.get("Stdout");
And print that String and see what happens.

Related

Convert Json String to List in Android

strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String

How to Read Json array values from file

JSONArray jsonArray = (JSONArray) obj;
When I use the above code, it shows the error message:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
Please anyone suggest any method to overcome this error or any other way to read json value form a file in Java (Desktop application).
Use this for get json value in string format from file
public String loadJSONFromFile() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JsonObject is a child of a JsonArray, so as per my suggestion use like this
final JSONArray jsonArray = new JSONArray();
jsonArray.put(obj); //obj is your JsonObject
and you can get JsonObject from array like
jsonArray.getJSONObject(0); //0 is index of your JsonObject in JsonArray
Hope this help you.
Check the content of the file.
It seems that the content is not an array, but a json object.
Open the file with a text editor. If the content is something like:
{ // First character
... content here
} // Last character
it is an object, if it is similar to
[ // First character
... content here
] // Last character
it is an array.
If you need to read an object you need to change your code as follow:
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) obj;
This obj is of JsonObject type, so change that line to
JSONObject jsonObject = (JSONObject)obj;

SimpleJson: String to JSONArray

I get the following JSON:
[
{
"user_id": "someValue"
}
]
It's saved inside a String.
I would like to convert it to a JSONObject which fails (as the constructor assumes a JSON to start with {). As this doesn't seem to be possible I'd like to convert it to a JSONArray. How can I do that with SimpleJson?
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
For your task you could use code as bellow:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says
JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
for (Object user : userdataArray) {
JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
String User_Id= (String)jsonrow.get("user_Id"); \\ Each User_Id will be displayed.
} else{
System.out.println("Empty Array....");
}
It works for me.
String jsonString = "[{\"user_id\": \"someValue\"}]";
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
try {
jsonArray = (JSONArray) parser.parse(js);
} catch (ParseException e) {
e.printStackTrace();
}

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"
}
]
}

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

I'm trying to parse below json file:
{"units":[{"id":42,
"title":"Hello World",
"position":1,
"v_id":9,
"sites":[[{"id":316,
"article":42,
"clip":133904
}],
{"length":5}]
}, ..]}
This is what I have tried:
Object obj = null;
JSONParser parser = new JSONParser();
Object unitsObj = parser.parse(new FileReader("file.json");
JSONObject unitsJson = (JSONObject) unitsObj;
JSONArray units = (JSONArray) unitsJson.get("units");
Iterator<String> unitsIterator = units.iterator();
while(unitsIterator.hasNext()){
Object uJson = unitsIterator.next();
JSONObject uj = (JSONObject) uJson;
obj = parser.parse(uj.get("sites").toString());
JSONArray jsonSites = (JSONArray) obj;
for(int i=0;i<jsonSites.size();i++){
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
System.out.println(site.get("article");
}
}
The code is not working when I try to parse the inner json array, so I get:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
The exception is pointing to this line:
JSONObject site = (JSONObject)jsonSites.get(i);
Any help? tnx.
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
If you don't need the array (like the author), you can simply use
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
The first element of the sites array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
this worked:
System.out.println("resultList.toString() " + resultList);
org.json.JSONObject obj = new JSONObject(resultList);
org.json.JSONArray jsonArray = obj.getJSONArray(someField);
for(int i=0;i<jsonArray.length();i++){
System.out.println("array is " + jsonArray.get(i));
}
JSONObject site=jsonSites.getJSONObject(i) should work out
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
#cyberz is right but explain it reverse
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
The return type of jsonSites.get(i) is JSONArray not JSONObject.
Because sites have two '[', two means there are two arrays here.
use your jsonsimpleobject direclty like below
JSONObject unitsObj = parser.parse(new FileReader("file.json");
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");

Categories