In Selenium, I'm using the JSON file to fetch the data and passing them into Getter methods of certain private variables, but it is throwing an error org.openqa.selenium.WebDriverException: unknown error: keys should be a string
Below are the lines of code :
public class ABC {
private String systemName;
JSONObject jsonObj = null;
public ABC() {
File filePath = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObj = jsonObject;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public String getSystemName() {
return (String) jsonObj.get("SystemName");
}
}
public class DEF {
ABC abc = new ABC();
String testString = abc.getSystemName();
}
Here the value of testString is set to null.
(All the required packages are imported)
Related
Hi I am working on a project it will show USD EUR TRY Bitcoin Gold values i have api for all of this values in json i want to sort them out my json link is this https://canlidoviz.com/doviz-kurlari.jsonld
I am parsing the json with this class
public class ClassJSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
public ClassJSONParser(){
}
public JSONObject getJSONFromURL(String url) {
try {
URL urlObject = new java.net.URL(url);
HttpURLConnection conn=(HttpURLConnection) urlObject.openConnection();
conn.setRequestMethod("GET");
is = new BufferedInputStream(conn.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
String tmp = line + "/n";
sb.append(tmp);
}
is.close();
json=sb.toString();
}catch (Exception e){
Log.i("Buffer Error","Error Converting Result"+e.toString());
}
try {
if(json !=null){
jObj=new JSONObject(json);
}else{
jObj=null;
}
}catch (JSONException e){
}
return jObj;
}
}
and getting a string like this
ClassJSONParser jParser = new ClassJSONParser();
String url = "https://canlidoviz.com/doviz-kurlari.jsonld";
jsonO= jParser.getJSONFromURL(url);
Log.d("***",jsonO.toString());
what method should i use how can i do can you give me guidance
I am having some problems push values from a JSON object. Here is my code
try {
JSONObject mainObject = new JSONObject(data);
lat = mainObject.getString("lat");
lng = mainObject.getString("lon");
} catch (JSONException e) {
e.printStackTrace();
}
Here is an example of a JSON string I will use.
{
"resource":[
{
"lat":"15.456082",
"lon":"75.020660",
"devid":"TEST",
"time":"2019-03-12 11:11:20",
"speed":"0.51856",
"pInt":"60",
"result":"SOS"
}
]
}
try {
JSONObject mainObject = new JSONObject(data);
JSONArray jsonArray = mainObject.getJSONArray("resource");
JSONObject resourceObject = jsonArray.getJSONObject(0);
String lat = resourceObject.getString("lat");
String lng = resourceObject.getString("lon");
String devid = resourceObject.getString("devid");
String time = resourceObject.getString("time");
String speed = resourceObject.getString("speed");
String pInt = resourceObject.getString("pInt");
String result = resourceObject.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject mainObject = new JSONObject(data);
JSONArray jsonArray = mainObject.getJSONArray("resource");
for(int i=0;i<jsonArray.length;i++ ){
JSONObject obj= josnArray.getJsonObject(i);
String lat = obj.getString("lat");
String lng = obj.getString("lon");
}
} catch (Exception e) {
e.printStackTrace();
}
Use Google's Gson instead. Here is full solution. It is life saving.
try {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(data).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("resource");
jsonObject = jsonArray.get(0).getAsJsonObject();
String lat = jsonObject.get("lat").getAsString();
String lng = jsonObject.get("lon").getAsString();
} catch (JsonIOException e) {
e.printStackTrace();
}
Im getting the next error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
class org.json.simple.JSONArray cannot be cast to class
org.json.simple.JSONObject (org.json.simple.JSONArray and
org.json.simple.JSONObject are in unnamed module of loader 'app')
The endpoint where im getting JSON is:
https://www.okex.com/api/spot/v3/instruments
I have searched about the error, I think the problem is that I am getting a JSONArray instead JSONObject, but I need to filter by key, as I need to get every "base_currency" from json.
Below is the original code which is giving me the error:
private String UrlBase = "https://www.okex.com/";
private URL url;
private String inline="";
private JSONObject jobj;
private JSONObject jobj1;
private Scanner sc;
private String Symbols = "api/spot/v3/instruments";
private String Param1= "base_currency";
private JSONArray arr;
private JSONArray arr1;
private JSONParser prs;
private HttpURLConnection conn;
private ArrayList Monedas = new ArrayList();
private Conexion conc = new Conexion();
public void CargarMonedasNuevasOkex() throws IOException {
try {
url = new URL(UrlBase+Symbols);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpURLConnection)url.openConnection();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if(responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " +responsecode);
}
else{
sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+= sc.nextLine();
}
sc.close();
JSONParser parse = new JSONParser();
try {
jobj1 = (JSONObject) parse.parse(inline);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr1 = (JSONArray) jobj1.get(Param1);
System.out.println(arr.get(0));
for( int a=0; a<arr1.size(); a++ ) {
jobj1 = (JSONObject) arr1.get(a);
}
}
}
instead of
arr1 = (JSONArray) jobj1.get(Param1);
do
arr1=job1 ;//or jsut use the same variable
oh and
jobj1 = (JSONObject) parse.parse(inline);
should be
jobj1 = (JSONArray) parse.parse(inline);
then
for( int a=0; a<arr1.size(); a++ ) {
JSONOBject temp= arr1.get(a));
String currency= temp.get("base_currency")
}
basically in the link provided you get a jsonArray not an Object containing an Array
for your requirement getting value according key,you can try this below code it is modified according your JSON format.
JSONParser parser = new JSONParser();
Object object = parser.parse(inline);
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject singleObject = (JSONObject) jsonArray.get(i);
System.out.println(singleObject.get("base_currency"));
}
My purpose is to parse twitter data which is described in JSON file. I created a void for parsing JSON which function perfectly, but it show me only one JSONObject while my `
public void parsingJson( String d) throws Exception
{
BufferedReader br = null;
//JSONObject rootObejct=null;
JSONObject js=new JSONObject();
try {
String sCurrentLine;
InputStream inputStream = new FileInputStream("E://inputdata.json") ;
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
br = new BufferedReader(inputStreamReader);
while ((sCurrentLine = br.readLine())!= null) {
JSONObject rootObejct=new JSONObject(sCurrentLine);
for(#SuppressWarnings("unchecked")
Iterator<String> iter = rootObejct.keys();iter.hasNext();) {
String key = iter.next();
try {
if (key.startsWith(d)){
System.out.println("******key*********"+key);
Object value = rootObejct.get(key);
System.out.println("keys vlaue "+value.toString());
}
} catch (JSONException e) {
// Something went wrong!
}
}
}
`
Here's a simple code to read a JSON file
public void readJSONFile(String filePath) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filePath));
JSONObject jsonObject = (JSONObject) obj;
//if your value is an array
JSONArray arr = (JSONArray) jsonObject.get("array");
//if your value is string
String str = (String) jsonObject.get("status");
} catch (Exception e) {
e.printStackTrace();
}
}
JSON file used as test case is
{
"status": "OK",
"array": [ "Hello" ]
}
If it doesn't help, please let me know.
I am currently parsing through reddit.com/.json with Google Gson and having some trouble. After doing some research I found a way to parse through json with Gson without making a lot of classes. I am using this method. Here is my code so far:
import java.io.*;
import java.net.*;
import com.google.gson.*;
public class Subreddits {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null){
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();//String of json
System.out.println(json);
//I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("data").getAsJsonObject("children").getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
System.out.println(subreddit);
}
}
You are trying to get the element "children" as a JsonObject, but it is a JsonArray because it is surrounded by [ ]...
Try something like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
//Here is the change
JsonObject locObj = rootObj
.getAsJsonObject("data")
.getAsJsonArray("children")
.get(0)
.getAsJsonObject()
.getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
Note: I assume that you only want to get the data of the first element of the "children" array, since it seems that it is what you want looking at your code and mainly looking at this other question of yours.
The children object returns an Array that you must iterate.
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null) {
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();// String of json
System.out.println(json);
// I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray locObj = rootObj.getAsJsonObject("data").getAsJsonArray("children");
/* Iterating children object */
Iterator<JsonElement> iterator = locObj.iterator();
while(iterator.hasNext()){
JsonElement element = iterator.next();
JsonElement subreddit = element.getAsJsonObject().getAsJsonObject("data").get("subreddit");
System.out.println(subreddit.getAsString());
}
}
You don't need to create try..catch block for every expression that can throw an exception.
JsonParser.parse() method accepts Reader (e.g. InpustStreamReader) instance so you don't have to read JSON on your own.
root[data][children] is an array of objects so you'll have to iterate over them in order to gain access to individual objects.
I believe you want to read all [subredit]s into some sort of collection, Set I pressume?
public static void main(String[] args) {
try {
Set<String> subreddits = new HashSet<>();
URL url = new URL("http://www.reddit.com/.json");
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(new InputStreamReader(url.openConnection().getInputStream())).getAsJsonObject();
JsonArray children = root.getAsJsonObject("data").getAsJsonArray("children");
for (int i = 0; i < children.size(); i++) {
String subreddit = children.get(i).getAsJsonObject().getAsJsonObject("data").get("subreddit").getAsString();
subreddits.add(subreddit);
}
System.out.println(subreddits);
} catch (IOException e) {
e.printStackTrace();
}
}
This code returns:
[IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]