how to parse arrays with direct values, twice json encoded - java

How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"

Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.

If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.

Related

Best way to manipulate the string inside a JSONArray

I have a JSON array built from objects added to a JSON object which I would like to slightly modify to get in the desired format.
Code Snippet:
JSONObject jobj = new JSONObject();
JSONArray jarr = new JSONArray();
Object col = "name";
Object num = 3;
Object val = "{set:" + num + "}";
jobj.put(col, val);
jarr.add(jobj);
System.out.println("what is jarr: " +jarr);
The output for the above code is the following:
what is jarr: [{"name":"{set:3}"}]
And, I would like the jarr array to be in this way instead:
[{"name”:{“set”:”3”}}]
Using a \" or '"' is including that character as well. Also, I am not able to get rid of the enclosing double quotes for the value of name. It is always recognizing it as a string and adding the enclosing double quotes for {set:3}.
Is there a good way to get the jarr in the above-mentioned format?

iterate through an a json value containing an array to pick an image string

I am able to fetch values the db and pass it to a string array as shown
String[] strArrayCol = new String[6];
strArrayCol[4] = json_data.getString("images");
if you print the above you gets:
[{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/yi6ej6f524bepyujh49y.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/wendzj5atiks45c3zw00.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/rg04t5vcp4yxwdew677n.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/3yvy9f970vit2pxascv7.png"}]
my attempt is on performing something like
ArrayList<String[]> imgCol...
imgCol.add(strArrayCol );
for (String [] val : imgCol){
System.out.println( val[4]);
}
let it prints
http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/yi6ej6f524bepyujh49y.png
http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/wendzj5atiks45c3zw00.png
http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/rg04t5vcp4yxwdew677n.png
http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/3yvy9f970vit2pxascv7.png
please how can I achieve this
Based on your code and explanation, it seems you are JSON object "images" is the below string:
{images:[{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/yi6ej6f524bepyujh49y.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/wendzj5atiks45c3zw00.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/rg04t5vcp4yxwdew677n.png"},{"path":"http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/3yvy9f970vit2pxascv7.png"}])}
Which is a JSONArray for the value of images.., Your code should be like this to retrieve the value of path
I have removed extra backward slashes in the string.
JsonImplement.parseJson("{\"images\":[{\"path\":\"http://10.0.2.2:88//web/uploads/images/yi6ej6f524bepyujh49y.png\"},{\"path\":\"http://10.0.2.2:88//web/uploads/images/wendzj5atiks45c3zw00.png\"},{\"path\":\"http://10.0.2.2:88//web/uploads/images/rg04t5vcp4yxwdew677n.png\"},{\"path\":\"http://10.0.2.2:88//web/uploads/images/3yvy9f970vit2pxascv7.png\"}]}");
And this is the logic I wrote in another method...
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
JSONArray arr = (JSONArray) jsonObject.get("images");
for(int i=0;i<arr.size();i++)
{
JSONObject obj2 = (JSONObject) arr.get(i);
System.out.println(obj2.get("path"));
}
This will give you output of image path's
http://10.0.2.2:88//web/uploads/images/yi6ej6f524bepyujh49y.png
http://10.0.2.2:88//web/uploads/images/wendzj5atiks45c3zw00.png
http://10.0.2.2:88//web/uploads/images/rg04t5vcp4yxwdew677n.png
http://10.0.2.2:88//web/uploads/images/3yvy9f970vit2pxascv7.png
If you know that your image file names will always be formatted as follows:
{path}/{filename}
Then there is a simple technique to find the file name.
Find the last slash (/) character in the string.
The filename is everything that follows the last slash character.
For example:
http:\/\/10.0.2.2:88\/\/web\/uploads\/images\/yi6ej6f524bepyujh49y.png
has a "path" value of "http://10.0.2.2:88//web/uploads/images/"
and a "filename" value of "yi6ej6f524bepyujh49y.png"

Fetching json response in jmeter using beanshell

In my jmeter response i have javascript and json as a mix response from that i have to fetch a JSON array which is items
Here is part of a huge response which i am getting
DE.APP.task.TaskGrid.getAssignmentData = function () {
return {"items":[]};
};
DE.APP.task.TaskGrid.getResourceData = function () {
return {"items":[{"STANDARDRATEFORMAT":"0.00","ASSIGNED_HRS":0,"RESOURCE_NAME":"#Buddhika ","COST":"0.00","PERCENTASSIGNED":"100.00","EMAIL":"Buddhika75#mspblank.com","AVAILABLEFROM":"10-May-2011","ALLOCATED_HRS":"1872.00","RESOURCE_ID":36197221,"AVAILABLETO":"31-Mar-2012","calendar":{"exceptions":{},"weekDayHours"
In this response i have to fetch the json array which is in getResourceData() and not any other items.
How can we do this with beanshell assrtion?
You can use apache StringUtils to cut the string using a left boundary and a right boundary. Your left boundary is clear "return {" but I am not sure about your right boundary (the string that follows your JSON payload). In the below example, I've used the ]} as the delimiter to cut your JSON payload. Use prev.getResponseDataAsString() to pull the response payload as a string.
import org.apache.commons.lang3.StringUtils;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;
String sInputString = "return {\"items\":[{\"STANDARDRATEFORMAT\":\"0.00\",\"ASSIGNED_HRS\":0,\"RESOURCE_NAME\":\"#Buddhika \",\"COST\":\"0.00\",\"PERCENTASSIGNED\":\"100.00\",\"EMAIL\":\"Buddhika75#mspblank.com\",\"AVAILABLEFROM\":\"10-May-2011\",\"ALLOCATED_HRS\":\"1872.00\",\"RESOURCE_ID\":36197221,\"AVAILABLETO\":\"31-Mar-2012\",\"calendar\":{\"exceptions\":{},\"weekDayHours\":{}}}]}";
//String sInputString = prev.getResponseDataAsString();
try {
// Use StringUtils to cut the string between the two
String sCutString = StringUtils.substringBetween(sInputString, "return {\"items", "]}");
String sFinalString = "{\"items" + sCutString + "]}";
log.info("sFinalString=" + sFinalString);
// Use JSONParser to parse the JSON
JSONParser parser = new JSONParser(JSONParser.ACCEPT_NON_QUOTE|JSONParser.ACCEPT_SIMPLE_QUOTE);
JSONObject rootObject = (JSONObject) parser.parse(sFinalString);
//JSONObject rootObject = (JSONObject) parser.parse(prev.getResponseDataAsString());
JSONArray jResourceArray = (JSONArray) rootObject.get("items");
for (int i=0; i < jResourceArray.size(); i++) {
log.info(jResourceArray.get(i).toString());
// You can access individual elements using this
log.info("RESOURCE_ID=" + jResourceArray.get(i).get("RESOURCE_ID"));
}
}
catch ( Exception ex) {
log.info("Exception.." + ex);
}
You can extract any part of the response using Regular Expressions. As action is need to perform on the response of particular request[sampler], you should use Post-Processors as child of that particular request. So basically use Regular Expression Extractor.
Assuming that your response is like this---
I have completed array of JSON object and added some tell which may be there. This is assumption that I'm making. Please check your actual response.
DE.APP.task.TaskGrid.getAssignmentData = function () {
return {"items":[]};
};
DE.APP.task.TaskGrid.getResourceData = function () {
return {"items":[{"STANDARDRATEFORMAT":"0.00","ASSIGNED_HRS":0,"RESOURCE_NAME":"#Buddhika ","COST":"0.00","PERCENTASSIGNED":"100.00","EMAIL":"Buddhika75#mspblank.com","AVAILABLEFROM":"10-May-2011","ALLOCATED_HRS":"1872.00","RESOURCE_ID":36197221,"AVAILABLETO":"31-Mar-2012","calendar":{"exceptions":{},"weekDayHours":{}}}]}
AnotherBlockthatYouCanIDenity
So you can have Post-Processor like this-
Please note that this RE may not be correct as i'm not sure about the response you are getting. Please check your response. You can test your regular expression in View Results Tree listener also.

Extract values from Json

I am using org.json.simple.JSon and I have a JSON Array of JSON objects like this:
{"longitude:":-1.0,"latitude:":1.0},
{"longitude:":1.0,"latitude:":1.0},
{"longitude:":1.0,"latitude:":-1.0},
{"longitude:":-1.0,"latitude:":-1.0}
I need to extract values for longitudes and latitudes in to a list like this
[-1.0,1.0]
[1.0,1.0]
Is there a way to do so using Json or using regex?
It's very simple. Just create JSONArray from JSON string and get the JSONObject at each index of JSONArray and get the desired values.
Note: enclose the string [...] to make it valid JSON string.
sample code:
String json = "[{\"longitude:\":-1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":1.0}]";
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("longitude:" + jsonObject.getDouble("longitude:"));
System.out.println("latitude:" + jsonObject.getDouble("latitude:"));
}
Valid JSON string: (Notice the colon : used in key as well)
[
{
"longitude:": -1,
"latitude:": 1
},
{
"longitude:": 1,
"latitude:": 1
}
]
Try something like this (uses json.simple like you need but note that there are other JSON Java libraries that might even be better):
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class PrintJsonArray {
public static void main(String[] args) throws ParseException {
String s = "[{\"longitude:\":-1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":-1.0},{\"longitude:\":-1.0,\"latitude:\":-1.0}]";
JSONArray array = (JSONArray) new JSONParser().parse(s);
List<String> l = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
JSONObject json = (JSONObject) array.get(i);
double longitude = (double) json.get("longitude:");
double latitude = (double) json.get("latitude:");
l.add("[" + longitude + "," + latitude + "]");
}
System.out.println(l);
}
}
Please note 2 things:
In order for the JSON you supplied to be a valid one you need to add '[' and ']' surrounding your JSON.
You have an ':' in the longitude/latitude attribute names - not sure that this is what you meant (but of course this is only cosmetic)...
^.*?(?=longitude:":).*?(-?\d+\.\d+).*?(?=latitude:":).*?(-?\d+\.\d+).*$
Try this.This will give you all the values.
See demo.
http://regex101.com/r/sM9gJ5/1

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Categories