Convert JSON String to Arraylist for Spinner - java

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)

I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.

Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}

You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}

For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});

Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}

You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

Related

Converting string to JSONArray, and then to list

I have String "[{...}]" and I want convert it to JSONArray, and then to List list = new List I was trying this solution, and this is my code
public void RestoreData()
{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<myClass> listdata = new ArrayList<myClass>();
JsonObject jsonObject = new JsonObject();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
}
And when I'm trying to compile this I get 2 errors:
In JSONArray jArray = (JSONArray)jsonObject; I get error 'Incovertible types; cannot cast 'org.json.JSONObject' to 'org.json.JSONArray'.
And second: in listdata.add(jArray.getString(i)); I get error 'unhandled exception org.json.JSONException'.
I'm new in Java and I work with Json for the first time.
EDIT
A small truncated example of the Json string:
[{"lootArmorGain":0,"lootBlockGain":0,"lootCost":93500,"lootCritGain":2,"lootCritPowerGain":0,"lootDamageAbsorptionGain":0,"lootDamageGain":0,
}]
I think what you want is:
public void RestoreData()
{
try{
String toConvert = "[{...}]" // I don't place full String, but it's typical JSONArray, but in String
ArrayList<MyClass> listdata = new ArrayList<MyClass>();
JSONArray jsonArray = new JSONArray(toConvert);
if (jsonArray != null) {
Gson gson = new Gson();
for (int i=0;i<jsonArray.length();i++){
String json = jsonArray.getJSONObject(i).toString();
MyClass obj = gson.fromJson(json, MyClass.class);
listdata.add(obj);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}
To convert from JSONOject to your custom class use GSON, see above.
compile 'com.google.code.gson:gson:2.8.4'
Note that your custom class need to have an empty constructor as well as getters and setters in order to make gson work.
I think best approach will be using Google Gson Library.
String toConvert = "[{...}]"
Type listType = new TypeToken<List<myClass>>() {}.getType();
List<myClass> yourList = new Gson().fromJson(toConvert, listType);
You dont need to get each position manually.
For simplicity you can also use Jackson api
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString,typeFactory.constructCollectionType(List.class, SomeClass.class));

Json object to java arraylist

I have pass two values from ajax to my servlet.
I used
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
and this is the output
{"0":"31/01/2017","1":"19/01/2017"}
Now I want to convert this data into a java arraylist but not really sure how.
I tried
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray();
// jsonArr.
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
But got an error
java.lang.IllegalStateException: This is not a JSON Array.
Someone help me please? thanks.
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.

Retrieving a Json String using the correct library

I'm trying to get the content of msg which is ERROR. I'm doing that by transforming string return into an array.
Now the solution 1, works perfectly fine using import org.json.JSONArray;:
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
JSONArray array = new JSONArray(" [{\"type\":1, \"txt\":\"ERROR\"}]");
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
The above solution allows me tro retrieve the content of "txt", which is "ERROR".
However (below code) when I try to use the reutrn of String jsReturn = JSONArray.toJSONString(ret); I'm not capable to do that because the library I'm using doesn't support JSONArray.toJSONString, so I need to import org.json.simple.JSONArray; which in turn doesn't allow me to use array.getJSONObject(i) but both libraries org.json.simple.JSONArray and
org.json.JSONArray don't work together. Any workaround to get the desired outcome?
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
String jsReturn = JSONArray.toJSONString(ret);//output(using simple.JSONArray) --> [{"type":1, "msg":"ERROR"}]
JSONArray array = new JSONArray(jsReturn);
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
org.json.JSONArray has a toString() method that will output a JSON string. It also allows for indentation by using toString(int indent_factor)

What should i use to store multiple images?

What should i use to store multiple images that i retrieve from for loop? array or list? Is there any example functions that i can use? Below is my example for loop where i get my data.
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
for(int i = 0; i < uniObject.length(); i++) {
JSONObject rowObject = uniObject.getJSONObject(i);
co.img1 = ipAddress +"img/store/" + rowObject.getString("store_banner");
}
Use ArrayList<>(); It's away more flexible than the normal array;

How to store Json Array to Java ArrayList?

I am completely don't know Json. Now i am working in Android project. I know how to use ArrayList. I have Json file inside of my Asset folder in my Android Project.
So, now i need How to parse this file from assets folder and how to store it to ArrayList.
String json="Your Json";
JSONObject resultJson = new JSONObject(json);
JSONArray value = resultJson.getJSONArray(<Pass Your JsonOject Key here>);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < value.length(); i++)
{
JSONObject qstnArray = value.getJSONObject(i);
list.add(qstnArray.getString("question"));
}

Categories

Resources