How to convert JSONArray to Java String Array [duplicate] - java

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

Related

Get Arraylist file json using java

I have problems with my code, I need to extract the "materias" markup in the arraylist. Example data:
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
I tried this, work but i need the content of the arraylist:
try { // this read the JSON file
line = new String(Files.readAllBytes(Paths.get("fileAulas")));
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray recs = new JSONArray(line);
for (Object rec : recs) {
Aula datos = new Aula();
JSONObject obj = ((JSONObject) rec);
String name = obj.getString("name");
//datos.setNombre(name);
String grupo = obj.getString("grupo");
//datos.setGrupo(grupo);
int tutor = obj.getInt("tutor");
//datos.setTutor(tutor);
}
My objetive is to read the arraylist and then datos.setArraylist to my another class. All works fine except read the arraylist
PD: I use java downloaded from Maven, to execute i use "javac -cp ./*: program.java"
materias is also an array, so you need something like:
JSONArray materias = obj.getJsonArray("materias");
List<String> materiasList = materias.getValuesAs(String.class);
This is not type-safe so you need to make sure the array will only have String values.
Also, if you are using Java 8, you can iterate over the values and store them manually (JsonArray is also a Collection<JsonValue>)
Quickly created short test implementation of your needs:
String json = "[{ \"name\":\"A114\",\"grupo\": \"DAW2\",\"tutor\":15,\"materias\": [\"DWES\",\"DWEC\",\"IW\",\"DAW\",\"IE\"]}]";
JSONArray objectArray = new JSONArray(json);
for (int x = 0; x < objectArray.length(); x++) {
JSONObject obj = objectArray.getJSONObject(x);
System.out.println("Name: " + obj.get("name"));
System.out.println("Grupo: " + obj.get("grupo"));
System.out.println("Tutor: " + obj.get("tutor"));
JSONArray materias = obj.getJSONArray("materias");
for (int y = 0; y < materias.length(); y++) {
System.out.println("Materia " + y + ": " + materias.get(y));
}
}
Output
Name: A114
Grupo: DAW2
Tutor: 15
Materia 0: DWES
Materia 1: DWEC
Materia 2: IW
Materia 3: DAW
Materia 4: IE
First gotta make your JSON Valid.
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
Secondly, you can try the following :
for (JsonElement rec : recs) {
Aula datos = new Aula();
JSONObject obj = rec.getAsJsonObject();
String name = obj.get("name").getAsString();
//datos.setNombre(name);
String grupo = obj.get("grupo").getAsString();
//datos.setGrupo(grupo);
int tutor = obj.get("tutor").getAsInt();
JsonObject obj = rec.getAsJsonObject();
JsonArray materias = obj.getAsJsonArray("materias");
List<String> materiasList = new ArrayList<>();
for (JsonElement item:
materias) {
materiasList.add(item.getAsString());
}
}
I believe that the syntax for an array in json is different that what you have in your file. For example - a simple complete json that contains an array of simple elements would be:
{"contacts":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Jen", "lastName":"Smith" },
{ "firstName":"David", "lastName":"Jones" }
]}
In your text, you specify an array, without the opening and closing JSON '{' and '}'. Also, You would need to name the array element ("contacts" in the example above). I think that what you want would be (I used "arrayName" for the array element name):
{"arrayName":[{ "name":"A114","grupo": "DAW2","tutor":15,"materias":["DWES","DWEC","IW","DAW","IE"] },
{ "name":"121","grupo": "DAW1","tutor":8,"materias":["PROGRA","BD","SIS","LM","FOL"] },
{ "name":"A112","grupo": "AUTO1","tutor":5 },
{ "name":"A127","grupo": "ASIR1","tutor":2 },
{ "name":"A114","grupo": "SMR2","tutor":11 },
{ "name":"A128","grupo": "ASIR2","tutor":9,"materias":["IAW","ABD","ASIS","SI","IE"] },
{ "name":"A125","grupo": "ADM2","tutor":12 } ] }

Getting random string from JSON File

Trying to get a random word from this JSON file
public class Main {
public static void main(String[] args) {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/adjs.json");
JSONArray jsonArray = obj.getJSONArray("adjs");
for(int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.get(i));
}
Random r = new Random();
int id1 = r.nextInt(jsonArray.length());
String word1 = jsonArray.getJSONObject(id1).getString("adjs");
System.out.println(word1);
//String word = jsonArray.getJSONObject(r.nextInt(jsonArray.length())).getString("adjs");
}
}
There is the code I am using and I keep getting this error.
Exception in thread "main" org.json.JSONException: JSONArray[671] is not a JSONObject.
at org.json.JSONArray.getJSONObject(JSONArray.java:428)
at Job.Main.main(Main.java:23)
How can I achieve it?
Below is the JSON I'm working with:
{
"description": "A list of English adjectives.",
"adjs":
[
"Aristotelian",
"Arthurian",
"Bohemian",
"Brethren",
"Mosaic",
"Oceanic",
"Proctor",
"Terran",
"Tudor",
"abroad",
"absorbing",
"abstract",
"academic",
"accelerated",
"accented",
"accountant",
"acquainted",
"acute",
"addicting",
"addictive",
"adjustable",
"admired",
"adult",
"adverse",
"advised"
]
}
Looking for ways around it. Oh yea is just a little bit of the JSON file.
String word1 = jsonArray.getJSONObject(id1).getString("adjs");
The variable jsonArray contains a JSONArray, which contains strings, not nested JSONObjects. What you want is
String word1 = jsonArray.getString(id1);
The code you actually wrote expects JSON in the following form:
{
"description": "A list of English adjectives.",
"adjs":
[
{ "adjs": "Aristotelian" },
{ "adjs": "Arthurian" },
...
]
}
Mentioning the key "adjs" twice in your code could have been a clue :-)

Retrieve data from a json object with square brackets enclosing the value of some object [duplicate]

This question already has answers here:
How to parse JSON Array (Not Json Object) in Android
(11 answers)
Closed 5 years ago.
I have a Jsonobject that contain some values that were an Arraylist before converting it to Jsonobject
[{"id":4,"name":"shirt","attributeName":["size"],"attributeValue":["6-7"],"attributeStock":["3"]}]
how can get attributeName & attributeValue & attributeStock like an Arraylist
I solve it by this code (jsonFavorites is a String that contain several jsonobject same to that i post in the Question [{},{},{}])
try
{
JSONArray jsonArray=new JSONArray(jsonFavorites);
for (int i=0; i<jsonArray.length();i++)
{
JSONObject object=jsonArray.getJSONObject(i);
int id=object.getInt("id");
String name=object.getString("name");
JSONArray Namearray=object.getJSONArray("attributeName");
JSONArray Valuearray=object.getJSONArray("attributevalue");
JSONArray Stockarray=object.getJSONArray("attributeStock");
ArrayList<String> attributeName=new ArrayList<>();
ArrayList<String> attributevalue=new ArrayList<>();
ArrayList<String> attributeStock=new ArrayList<>();
for (intj=0; j<Namearray.length();j++)
{
attributeName.add(Namearray.getString(j));
attributevalue.add(Valuearray.getString(j));
attributeStock.add(Stockarray.getString(j));
}
}
}catch (Exception e){}

Comma is causing unwanted string split

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());

How to parse JSON array into an Android list [duplicate]

This question already has answers here:
JSON parsing using Gson for Java
(11 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
How to parse JSON in Java
(36 answers)
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
How to Parse a JSON Object In Android
(4 answers)
Closed 2 years ago.
I have a rather specific question about JSON parsing in Android.
I have a requirement to download a single JSON array containing information in the format shown below, the number of JSON objects in the array is variable. I need to retrieve all the JSON values in the array so each JSON value has to be stored as an android list named after the common JSON keys because there are many instances of each, e.g. a list for placenames keys [place1,place2,place3 = placename list], a list for questions key, etc. A caveat to this is I cannot use an android array to store these JSON key values since each time my app runs this download task I don't know how many JSON objects will be in the single array. Users can submit as much as they want at any time to the database.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
Below is my code for mainactivity which I managed to get working but had a derp moment and realised I'd simply gone through and parsed out the values for each JSON key in each object as a single string value for each JSON key. Since the loop iterates it merely overwrites at each stage - the placename string is "place1", then "place2", then "place3" by the end of the loop, rather than ["place1","place2", "place3"] which is what I want. My question now is how would I go about parsing the JSONArray to extract all instances of each JSON value and output as a string list for each JSON key, the length of the list is determined by the number of Objects?
I've already got the template for a string list that stores all the JSON key values (commented out in the below code) but I'm not sure how to fill that String list from the JSON parsing process.
I've had a good look around and couldn't find anything specifically about JSON Array to Android List so help would be greatly appreciated. I'd also like to know if there is a way of maintaining association between each list (e.g. questions & answers for specific placenames) if I bundle the data out to different activities (e.g. q&a to a quiz and placenames/lat/lon to GPS). Can I do this by referencing the same index in the list? Or would I need to store these lists in local storage? an SQL lite database?
Thanks for your time and sorry for the overwhelmingly long post!
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://www.example.php";
// Will hold the values I pull from the JSON
//static List<String> placename = new ArrayList<String>();
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//Log.v("JSONParser RESULT ", result);
try {
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
latitude = obj.getString("latitude");
longitude = obj.getString("longitude");
question = obj.getString("question");
answer1 = obj.getString("answer1");
answer2 = obj.getString("answer2");
answer3 = obj.getString("answer3");
answer4 = obj.getString("answer4");
correctanswer = obj.getString("correctanswer");
}
} catch (JSONException e){
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Instead of keeping variables:
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
make Bean Class having all these variables. Make array list of bean and during parsing make bean objects and add to list.
Bean Class:
public class ModelClass{
private String latitude = "";
private String longitude = "";
private String question = "";
private String answer1 = "";
private String answer2 = "";
private String answer3 = "";
private String answer4 = "";
private String correctanswer = "";
// ....
// Getter Setters and constructors
// .......
}
ArrayList<ModelClass> mList=new ArrayList<ModelClass>();
In for loop of json parsing:
JSONObject obj = array.getJSONObject(i);
ModelObject object=new ModelObject();
// parse and make ModelObject
list.add(object);
Try using this approach. It will work.
you should divide your objects into classes, and use the GSON json parser.
look at this answer on how to parse a json array into objects:
JSON parsing using Gson for Java
a good approach would be a class question that contains a list of subclasses called possibleanswers, those have a boolean attribute ( correct : true, incorrect: false) to check if the user has clicked the correct one.
if you want to store the data, you will have to use sqllite or any of the many libraries like ActiveAndroid.
I see that you are accessing this JSON file form a Remote Service. On that basis, you will need to structure your code in a manner that will work around how many instances are in the physical JSON file.
Your issue is here:
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
You are telling it that the entire JSON file has an array, which contains a length, which is incorrect.
Curly Brackets ("{") represent a JSONObject, and Square Brackets ("[") represent a JSON Array.
Based on your JSON file:
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
You are dealing with one JSONArray, and this array has to no reference name give to it, rather a place index.
Heres what you need to try:
public class ListCreator{
private List<String> placename;
public ListCreator() {
placename = new ArrayList<String>();
}
public void addPlaceName(String s)
{
answers.add(s);
}
public String[] getAnswers()
{
return placename.toArray(new String[1]);
}
}
Bear in mind that is just a snippet of what the class will look like only for the "placename" fields.
Now to your JSON:
You will need to initialize a Vector Variable for each List you want to create:
private Vector<ListCreator> placeNameVec;
Next you will need to set a method for each part of the JSONArray:
public Vector getPlaceNames(){
return placeNameVector;
}
JSONArray array = new JSONArray(result);
for(int x = 0; x < 3; x++){
JSONObject thisSet = array.getJSONObject(x);
ListCreator placeNames = new ListCreator();
placeNames.addPlaceName(thisSet.getString("placename"));
}
placeNameVec.add(placeNames);
That should get you going on what you are trying to answer.
So basically bear in mind that you you can't specify the "array.length()".
Hope this helps!
Please let me know of the outcome :)
If you get into any further difficulty, this Tutorial on JSONParsing really did help me when I was confused.
All the best

Categories