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.
Related
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.
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;
}
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
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");
i have a problem which i cant solve for days.
the String line input is "{"name":"John", "Hobby":"Cycle"}" sent from a JSON from PHP server
The code at android application
public void testFn()
{
try {
while ((line = reader.readLine()) != null) {
String tmp = gson.toJson(line.toString());
JSONObject jobj = (JSONObject)new JSONParser().parse(tmp);
sb.append(jobj.get(1).toString() + "\n");
}
}catch ....
}
i wanted to convert the string received and convert it to a JSONObject / JSONArray which i can retrieve it or display to TextView as a String format. but i keep getting the error of CastException from java.String to JSON.simple.JSONObject..
Hope someone could enlighten me on this
class MyJsonObject{
private String name;
private String Hobby;
MyJsonObject() {
}
}
MyJsonObject obj = new MyJsonObject();
Gson gson = new Gson();
String json = gson.toJson(obj);
(Deserialization)
MyJsonObject obj2 = gson.fromJson(json, MyJsonObject.class);
Try
String str = "{\"name\":\"John\", \"Hobby\":\"Cycle\"}";
//i wrote preceded "\" to very " because it is code format string,
//not came from internet. You can pass direct response from PHP server
try {
JSONObject json = new JSONObject(str);
Log.d("Home",json.getString("name"));
Log.d("Home",json.getString("Hobby"));
} catch (JSONException e1) {
e1.printStackTrace();
}
Basically now i edited my code here
String line = "{"name":"John","Hobby":"Cycle"}";
Object obj=parser.parse(line);
JSONArray array=(JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
System.out.println(obj2.get("name").toString());
sorry i figured out a way.
Output:
John