Best way to manipulate the string inside a JSONArray - java

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?

Related

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"

how to get data from JSONObject

This is the JSON i get access to:
[{"Nombre":"Craic Irish Pub","Descripcion":"Pub estilo Irlandes","Telefono":"234234","SitioWeb":"","Horario":"Viernes - Sabados 17:00- 24:00","Parqueo":"No","Ubicacion":"San Jose","Reservas":"Si","_id":"5449b3334d50a38754000003","__v":0}, {"Nombre":"TicoPub","Descripcion":"Pub Moderno","Telefono":"34534534","SitioWeb":"ticopub.com","Horario":"Viernes - Sabados 17:00- 24:00","Parqueo":"Si","Ubicacion":"Lindora","Reservas":"Si","_id":"5449b3cd4d50a38754000006","__v":0}]
i can read it and save it as a JSONObject (named json) however i can't do this:
JSONArray values = json.getJSONArray(0)
how can i access it?
You definitely cannot store that JSON in a JSONObject, since it is NOT a JSON object. It is a JSON array. So use a JSONArray to store it.
Based on what you typed I assumed you're using json.org's library. As Sotirios pointed out, whenever you have '[]' in a json string that means you're using array. You must first create a Json array and then you can access the individual object (you have two of them). See below:
String jsonString = "[{'Nombre':'Craic Irish Pub','Descripcion':'Pub estilo " +
" Irlandes','Telefono':'234234','SitioWeb':'','Horario':'Viernes - Sabados 17:00- 24:00'," +
"'Parqueo':'No','Ubicacion':'San Jose','Reservas':'Si','_id':'5449b3334d50a38754000003','__v':0}, " +
" {'Nombre':'TicoPub','Descripcion':'Pub Moderno','Telefono':'34534534','SitioWeb':'ticopub.com','Horario':'Viernes - Sabados 17:00- 24:00'," +
"'Parqueo':'Si','Ubicacion':'Lindora','Reservas':'Si','_id':'5449b3cd4d50a38754000006','__v':0}]";
JSONArray array = new JSONArray(jsonString);
JSONObject obj = array.getJSONObject(0);
String nombre = obj.getString("Nombre");
System.out.println(nombre); //prints 'Craic Irish Pub'

how to parse arrays with direct values, twice json encoded

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.

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" .

converting from String to JSONArray or JSONObject in Java

I'm trying to use the JSON library to consume twitter information from the get search feature. I'm getting the error:
A JSONArray text must start with '[' at 1 [character 2 line 1]
So it's basically in the wrong form. Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. How do I get this string into the form of a JSONArray so that I can access it's elements.
Here is my code:
URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
my print statement shows the string contains:
{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................
This is a string in the form of a JSON object but it is not actually an object. It's still a string. I'm printing a String. HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements.
That's a JSON object, not an array.

Categories