This question already has answers here:
Convert JSONArray to String Array
(18 answers)
Closed 2 years ago.
I want to extract authors from this JSON, I successfully get the JSONArray but I don't know how to convert it into String[], I have to pass this String[] to a method. Please try to keep the solution simple as I am just a beginner.
JSON :
{
"volumeInfo": {
"title": "Android",
"authors": [
"P.K. Dixit"
]
}
}
Code:
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
// Extract the value for the key called "title"
String title = volumeInfo.optString("title");
// Extract the array for the key called "authors"
JSONArray authors = volumeInfo.optJSONArray("authors");
private ArrayList<String> authorarray = new ArrayList<String>();
for (int i = 0; i < authors.length(); i++) {
String author = authors.getString(i);
//add author to your array
authorarray.add(author);
}
Use this function
String[] authors_arr(JSONArray authors){
String[] authors_res=new String[authors.length()];
try {
for(int i=0;i<authors.length();i++)
{
authors_res[i]=authors.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return authors_res;
}
call it like this String[] authors_string_array = authors_arr(authors);
The main point is to loop through your json array and add it into your array
This question already has answers here:
How can I turn a JSONArray into a JSONObject?
(4 answers)
Closed 4 years ago.
I am writing a rest java service. I want to convert my JSONArray to JSONObject and return it. But I am getting "{}" as output when I hit my rest service from browser. Although it is printing fine inside rest service when i tried to print using System.out.println();
PreparedStatement dimDelPS = null;
ResultSet dimDelRS = null;
dimDelPS = connection.prepareStatement("select * from abc");
dimDelRS = dimDelPS.executeQuery();
String dimLow=null;
while (dimDelRS.next()) {
int total_rows = dimDelRS.getMetaData().getColumnCount();
for (int i = 0; i < total_rows; i++) {
org.json.JSONObject obj = new org.json.JSONObject();
obj.put(dimDelRS.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), dimDelRS.getObject(i + 1));
jsonArray.put(obj);
}
}
System.out.println("json1 :"+jsonArray);
//Sample output at this stage: ["{\"employee\":\"ANTHONY.DUNNE\"}","{\"type\":\"Manager\"}"]
dimDelRS.close();
dimDelPS.close();
JSONObject jsobobject= new JSONObject();
jsobobject.put("aoColumnDefs",jsonArray);
System.out.println(jsobobject);
return jsobobject;
You can't just return JSONObject.
You need to male sure you Marshall it into json.
'return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).build();'
Browser understand String, and not java object.
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:
public List getAnswerStringEdit() {
return answer_edit;
}
I save it as so:
editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
Then retrieve it here:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
answerString = answerString.substring(1, answerString.length() - 1).trim();
String[] array = answerString.split(",");
Finally, I access the array as so:
et_answer1_edit.append(array[0]);
My problem is this - Say I add a questions which has a comma in the middle of it, like -
Question 1- "Why is this broke, I don't know?"
Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:
"Why is this broke, I don't know?"
However, instead I am getting in position 0:
Why is this broke - then position 1 as: I don't know
I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.
The retrieved JSON is as follows:
{
"result": "success",
"message": "Answer Has Been Selected",
"answer": {
"answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
}
}
Any help/advice that can help me to understand what is causing this, would be really appreciated.
Dont split the string using ',' use this
JSONObject jsonObject = new JSONObject(answerString );
JSONArray jsonArray = jsonObject.getJSONObject("answer").getJSONArray("answer_edit");
Log.e("Json Array elements are","First Element : "+jsonArray.get(0)+"\nSecond Element : "+jsonArray.get(1));
String QuestionString1 = jsonArray.get(0).toString();
String QuestionString2 = jsonArray.get(1).toString();
try this one
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject answer= jsonObject.getJSONObject("answer");
JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArrayAnswerEdit);
for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
String que= jsonArrayAnswerEdit.getString(i);
Log.e("json", i + "=" + que);
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this
JSONObject jsonObject = new JSONObject("your json response");
try
{
JSONObject data = jsonObject.getJSONObject("answer");
JSONArray jsonArray = data.getJSONArray("answer_edit");
Log.e("=>", "" + jsonArray);
for (int i = 0; i < jsonArray.length(); i++)
{
String value = jsonArray.getString(i);
String[] parts = value.split(Pattern.quote(","));
for (int j=0; j<parts.length; j++)
{
Log.e("Answer String ", "=" + parts[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
E/=>: ["Why is this broke, I don't know?","What is your favorite song, because I want to know"]
E/Answer String: =Why is this broke
E/Answer String: = I don't know?
E/Answer String: =What is your favorite song
E/Answer String: = because I want to know
After reading all the suggest answers, figured out a simple solution:
First I stored my answers sent from my external database as so -
final String jsonAnswers = gson.toJson (resp.getAnswer().getAnswerStringEdit());
Then saved in shared pref -
editor.putString(Constants.ANSWER_EDIT,jsonAnswers);
Next to read the answer back out:
String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
final String[] array = gson.fromJson (answerString, String[].class);
Finally, I could set my Edittext with data from the array:
et_answer1_edit.append(array[0].trim());
et_answer2_edit.append(array[1].trim());
This question already has answers here:
IndexOutOfBound Exception throwing Android
(2 answers)
Closed 7 years ago.
I have an error coming up and it's saying it is in this method pointing at the address list. Does anyone has a suggestion why this is happening and the app crashes?
Appreciate it.
01-22 14:03:25.466 2271-2271/? E/AndroidRuntime:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
List<Address> addressList=null;
if (address!=null || !address.equals("")) {
Geocoder geocoder = new Geocoder(getActivity());
try {
addressList = geocoder.getFromLocationName(address, 1);
} catch (IOException e) {
e.printStackTrace();
}
}
if (addressList != null){
Address addresses = addressList.get(0);
// my address lng and lgnt
latLngOffers = new LatLng(addresses.getLatitude(), addresses.getLongitude());
latLocation = addresses.getLatitude();
longLocation = addresses.getLongitude();
// Log.d("Offer address", String.valueOf(latLocation));
}
// latOffer=53.3399009;
// Log.d("my location inside", String.valueOf(latOffer));
DecimalFormat df = new DecimalFormat("##.###");
df.setRoundingMode(RoundingMode.DOWN);
// System.out.println(df.format(latLocation));
Log.d("offer location", String.valueOf(df.format(longLocation)));
Log.d("my location inside", String.valueOf(df.format(longOffer)));
String loffer = df.format(latOffer);
String lonOffer = df.format(longOffer);
String llocation = df.format(latLocation);
String lngLocation = df.format(longLocation);
String lsearch = df.format(latSearch);
String lngsearch = df.format(longSearch);
If there are no elements in a list or array, you can not retrieve the first (non-existing) element.
The valid indices are:
0 -> (number of elements - 1)
If there are no elements, there is no valid index.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
String response = "{\"mon\" : [[16,20]],\"sun\":[[10,20]]}";
Basically, how do I get one object of 2 items where in each item is an int array of 2 elements. Sample code please.
JSONArray jsonArray = jsonObject.getJSONArray("mon");
JSONArray weekdayArray = jsonArray.getJSONArray(0);
int size = weekdayArray.length();
String weekday[] = new String[size];
int[] wday = new int[size];
for(int i=0; i < size ; i++) {
weekday[i] = weekdayArray.getString(i);
wday[i] = Integer.parseInt(weekday[i]);
}
Where you get this json? because this json format is incorrect,if you necessary validate this json , access the http://json.parser.online.fr/ e paste your json e verify if this json is correct.