Currently I am using netbeans IDE. I tried using other solution, but to no luck so far.
Problem is, i am facing errors when trying to read the Json file from google Chrome bookmarks file (C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Bookmarks)
p/s: although there is no file type written in the name of Bookmarks, its content have been known as JSON
This is the what inside the Bookmarks.json:
{
"checksum": "20fdfad51db6d3199f8a09c3220dd93b",
"roots": {
"bookmark_bar": {
"children": [ {
"date_added": "13124893413824227",
"id": "6",
"name": "YouTube",
"type": "url",
"url": "https://www.youtube.com/"
}, {
"date_added": "13124893435163243",
"id": "7",
"name": "Welcome to Facebook",
"type": "url",
"url": "https://www.facebook.com/"
} ],
"date_added": "13124893381424539",
"date_modified": "13124893435163243",
"id": "1",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [ ],
"date_added": "13124893381424547",
"date_modified": "0",
"id": "2",
"name": "Other bookmarks",
"type": "folder"
},
"synced": {
"children": [ ],
"date_added": "13124893381424550",
"date_modified": "0",
"id": "3",
"name": "Mobile bookmarks",
"type": "folder"
}
},
"version": 1
}
And here is my code (JsonParser.java):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser{
private static String jsonFile = "C:\\Users\\Admin\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks";
public static void main (String[] args) {
try {
FileReader reader = new FileReader (jsonFile); //access the file
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String c =(String) jsonObject.get("checksum"); //place
// String r =(String) jsonObject.get("roots"); //place
// String r =(String) jsonObject.get("children"); //place
System.out.println("check: " + c);
//System.out.println("roots: " + r);
JSONArray lang = (JSONArray) jsonObject.get("roots");
for (int i=0; i<lang.size(); i++) {
System.out.println ("Url Name : " + lang.get(i)+"\n");
} //data in the array
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
For some reason when I run the code these are the errors I got:
check: 4d55f8a0888f7dd918a702eda2821ccd
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
at JsonParser.main(JsonParser.java:28)
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:1051: The following error occurred while executing this line:
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 2 seconds)
As you can see, only checksum succeed in being read, but the roots failed and gave out these errors.
You should also notice that there are some codes I put as comments, those are things i tried but still got the errors.
I hope anyone can help me to get these things working.
Thank you very much for helping
Issue is , you cannot cast object to array like (JSONArray) jsonObject.get("roots"); you have to follow the structure so parse according to object and array as shown below
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String checksum =jsonObject.optString("checksum");
// get root object
JSONObject root = jsonObject.getJSONObject("roots");
// get root bookmarks object from root
JSONObject bookmarks = root.getJSONObject("bookmark_bar");
// get root children array from bookmarks
JSONArray childrens = bookmarks.getJSONArray("children");
JSONObject temp ;
for (int i=0; i<childrens.size(); i++) {
// get object using index from childrens array
temp = childrens.getJSONObject(i);
// get url
String url = temp.optString("url");
}
as your structure follow
JObject => root
root JSONObject has : bookmark_bar JSONObject
bookmark_bar JSONObject has : children JSONArray
children JSONArray has JSONObject which further has String: url
roots is not a JSONArray but a JSONObject.
So what you have to do is
JSONObject lang = jsonObject.get("roots");
and then you have too loop through all keys in the object which should be:
bookmark_bar
other
synced
It seems to me like "roots" is not an array, but an object when looking at the JSON. "children" under "bookmark_bar" is an array however
Related
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
How to structure Multiple array of JSON in the beanshell sampler
for example i need to pass N number of articles to a loop , so i have created a for loop to fetch the articles. here i have mentioned 3 articles as an example. but i need to fetch N number of articles in a loop.
The output should be like :
"itemLines": {
"itemLine": [
{
"bundleParentId": "",
"id": "1",
"itemType": "ART",
"itemNo": "1234",
},
{
"bundleParentId": "",
"id": "2",
"itemType": "ART",
"itemNo": "2021",
},{
"bundleParentId": "",
"id": "3",
"itemType": "ART",
"itemNo": "2023",
}
]
}
My code in the beanshell smpler is : For example here i have mentioned in the array list with 3 article numbers.
public void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray articleArr = new JSONArray();
String[] article_list = {"00258882", "70234185", "00258882"};
log.info(article_list.length);
for (i=0;i<=article_list.length;i++)
{
JSONObject article_list= new JSONObject();
article_list.put("id", "i+1");
article_list.put("itemNo",article_list[i]);
article_list.put("requiredQty", "1");
articleArr.put(article_list);
}
log.info(articleArr);
rootObject.put("itemLines", articleArr);
log.info("rootObject is"+rootObject.toString(4));
props.put("JsonObjectoutput", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
log.info("notes");
}
}
I could see the output is not retrieved in the jmeter logs . Here output should be printed in the logs , but i could see output is not printed.
I am having trouble parsing a simple json in java. Here is the sample json.
[
{
"politics": [
{
"type": "admin2",
"friendly_type": "country",
"name": "United States",
"code": "usa"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Gratiot",
"code": "26_057"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Eighth district, MI",
"code": "26_08"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Clinton",
"code": "26_037"
},
{
"type": "admin4",
"friendly_type": "state",
"name": "Michigan",
"code": "us26"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Fourth district, MI",
"code": "26_04"
}
],
"location": {
"latitude": 43.111976,
"longitude": -84.71275
}
}
]
Now this gives me the correct json index.
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
String jsonobj = array.get(0).toString();
{"politics":[{"code":"usa","name":"United States","type":"admin2","friendly_type":"country"},{"code":"26_057","name":"Gratiot","type":"admin6","friendly_type":"county"},{"code":"26_08","name":"Eighth district, MI","type":"constituency","friendly_type":"constituency"},{"code":"26_037","name":"Clinton","type":"admin6","friendly_type":"county"},{"code":"us26","name":"Michigan","type":"admin4","friendly_type":"state"},{"code":"26_04","name":"Fourth district, MI","type":"constituency","friendly_type":"constituency"}],"location":{"latitude":43.111976,"longitude":-84.71275}}
But I cant seem to get the attribute that I want from it.
JSONObject obj1 = new JSONObject(jsonobj);
String n = obj1.getString("admin4");
System.out.println(n);
All that I need from this json is the state which is Michigan. Where am I wrong?
Help would be really appreciated.
First, array.get(0) will get you the first element from the main array. This first element is a JSON object that has two properties politics and location. You seem to be interested in a value that is inside the array value of the politics property. You'll have to use this ((JSONArray)((JSONObject)array.get(0)).get("politics")) to get that array.
Second, admin4 is not a property it is actually a value of the type property. You'll have to loop through the array to find it.
Here is a complete example:
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
JSONArray politics = ((JSONObject)array.get(0)).get("politics"));
JSONObject obj = null;
for(int i = 0; i < politics.size(); i++){
if(((JSONObject)politics.get(i)).getString("type").equals("admin4")){
obj = ((JSONObject)politics.get(i));
}
}
if(obj != null){
// Do something with the object.
}
It seems that you're using the simple json library. I don't remember exactly if it is .get("politics") or .getJSONObject("politics"). There may be other mistakes in method names in my example.
the best solution to simplify your search and other operations on json object, is the convert json string to java object and doing your operations.
for convert json string to java object use follow code:
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
YourObject myObject;
ObjectMapper mapper = new ObjectMapper();
try{
myObject= mapper.readValue(jsonData, myObject.class);
}
catch (Exception e) {
e.printStackTrace();
}
for example define your class ass follow :
public class myObject{
private List<Politics> politics;
private Location location;
// define getters and setters
}
define Politics and Location class:
public class Politics
{
String type;
String friendly_type;
String name;
String code;
// define getters and setters
}
public class Location
{
String latitude;
String longitude;
// define getters and setters
}
It's because your are trying to get the inner element of the JSON Object.
try
JSONObject obj1 = new JSONObject(jsonobj);
JSONArray arr = (JSONArray) obj1.getObject("politics");
You will get a JSONArray object which further constitutes of JSON objects.
Now in order to get values using the key you must iterate array as given below:
for(int i=0; i<arr.size(); i++){
JSONObject obj = arr.getJSONArray(i);
System.out.println(obj.getString("type"));
}
which will now provide you with output:
admin2
admin6
constituency
admin6
admin4
constituency
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want to parse a JSON file in java and get the following values from the file mentioned below:
{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {
"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"
}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"
}
} ]
} ]
}
From every element, i want to get the value field of both distance and duration. How do i do this?
Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.
package com.mypackage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";
try {
JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject row = rows.getJSONObject(i); // Get row object
JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array
for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
JSONObject element = elements.getJSONObject(j); // Get the element object
JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
JSONObject distance = element.getJSONObject("distance"); // Get distance sub object
System.out.println("Duration: " + duration.getInt("value")); // Print int value
System.out.println("Distance: " + distance.getInt("value")); // Print int value
}
}
} catch (JSONException e) {
// JSON Parsing error
e.printStackTrace();
}
}
}
Create an class structure that reflects the JSON
Use a library like Jackson or GSON to deserialize the json to instances of your classes.
If you want a more dynamic approach, the above frameworks can also serialize to maps.
Use a library for working with JSON. For example google-gson.
as Bozho said create class structure that reflacts JSON and then use jacson library as follow:
refer Parsing JSON File Java
ObjectMapper mapper = new ObjectMapper();
Projects projs =
mapper.readValue(new File("projects.json"),Projects.class);
ArrayList<Project> projects = projs.get("projects");
for (Project p : projects) {
ArrayList<String> description = p.getDescription();
for (String s : description) {
System.out.println(s);
You can use a library like JSON-java
import org.json.JSONObject;
String jsonString = ...
JSONObject object = new JSONObject(jsonString);
String status = object.getString("status");
You can use :
org.bson.Document d = org.bson.Document.parse("{ foo: \"bar\" }");
yes you can use jacson to parse it but there is more easy way to do it
its Jsonme lib "import org.json.me" you dont have to add jar file to use it
JSONObject obj = new JSONObject("{'var1':'val1','var2':200});
String var1=obj.getString("var1");
int var2=obj.getInt("var2");
yes its more easy but if your project is complex i advice you to use jacson lib