Convert Json String to List in Android - java

strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod

Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}

Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0

This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123

below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]

Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String

Related

How to post this type of data in JSON Object

I have to post this type of data into Json. I don't want to convert cat in string. I only want single quote of item enclosing with double quote.
{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
My Json
JSONObject jsonobject1 = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
jsonobject.put("ovpsc7s", jsonobject1);
jsonobject1.put("cat", hCategory);
Here hCategory is Hashset.
I want to json like this
{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}
JSONObject jsonobject = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
try {
jsonobject1.put("cat", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonobject.put("ovpsc7s", jsonobject1);
String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat"); // contains ["'Furniture'", "'Bikes'", "'Others'"]
String first = jsonCatArray.getString(0); // contains 'Furniture'

How to get values from JSONObject in Java?

I am trying to parse a JsonArray and get its values but I am gettign error when I use
jitem.getString("firstitem");
or
jitem.getJSONObject("firstitem");
or
jitem.get("firstitem");
Following is the code snippet.
JSONArray arr_items = new JSONArray(str);
if(arr_items!=null && arr_items.size()>0){
for(int i=0;i<arr_items.size();i++){
JSONObject jitem = arr_items.getJSONObject(i);//works fine till here
jitem.getString("firstitem"); //throws exception here
}
This is the JSONArray that I am parsing
[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf#sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]
what I am doing wrong? How to get these values by using keys?
Update:Note This array and its parameters are not null at all. They all have valid values.
First check arr_items is not empty.
Then, try surrounding your snippet with try/catch :
try {
your snippet
} catch (JSONException e) {
e.printStackTrace();
}
Check below
String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf#sjhasjkdsha.com','fourthitem':'jkksdjklsfjskj'}]"+ "}";
JSONObject myjson = new JSONObject(json);
JSONArray the_json_array = myjson.getJSONArray("array");
int size = the_json_array.length();
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
// arrays.add(another_json_object);
System.out.println(another_json_object.get("firstitem"));
}
it require some array name so appended array name to it , if you want without it you have to add GSON.

Convert returned JSON String to a JSONArray

I have a web service that performs a database query, converts the result set to a JSON String and returns the strung to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/):
public static String convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.add(obj);
}
return jsonArray.toJSONString();
}
In the client application when I print the returned string it is in the following format:
[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]
so far all is good. The problem I am having is converting the returned string into a JSON array. I tried this:
JSONArray arr = new JSONArray(JSON_STRING);
but got the following error message: constructor JSONArray in class JSONArray cannot be applied to given types. I tried to first convert in into a JSON object like so:
JSONObject obj = new JSONObject(JSON_STRING);
but got the following error: incompatible types: String cannot be converted to Map. What am I doing wrong? Thanks.
Apparently the problem was with the json library that I was using. Once I used the
import org.json.JSONArray;
it all worked out well. I was able to convert the returned string to an array using
JSONArray arr = new JSONArray(JSON_STRING);
and to iterate through the values I used the code provided in this answer: Accessing members of items in a JSONArray with Java which I reproduce here for simplicity:
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
well you need to do it by this way for example
String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try {
JSONArray array = new JSONArray(jsonText);
System.out.println(array);
System.out.println(array.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Check the correct library used. The mess is that org.json.simple is often suggested by IDE as default for JSONObject and JSONArray.
You can find a link to latest jar for org.json library above.

How to write a JSONObject to a file, which has JSONArray inside it, in Java?

I have JSON file, that I need to read, edit and write out again.
Reading works fine, I struggle with the write part of the JSON Array in my data.
I use JSON.simple library to work with JSON in Java.
The file looks like this:
{
"maxUsers":100,
"maxTextLength":2000,
"maxFileSize":2000,
"services":
[
{
"serviceName":"Яндекc",
"className":"YandexConnector.class",
"isEnabled":true
},
{
"serviceName":"Google",
"className":"GoogleConnector.class",
"isEnabled":false
}
]
}
When I try to write JSON-data (variable obj) to file, the services array is broken. My writing code:
JSONObject obj = new JSONObject();
obj.put("maxUsers", this.getMaxUsers());
obj.put("maxTextLength", this.getMaxTextLength());
obj.put("maxFileSize", this.getMaxFileSize());
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i));
}
obj.put("services", servicesJSON);
FileWriter file = new FileWriter(filename);
obj.writeJSONString(file);
file.flush();
file.close();
This outputs:
{
"services":
[
translator.settings.Service#121c5df,
translator.settings.Service#45f4ae
],
"maxTextLength":2000,
"maxUsers":100,
"maxFileSize":2000
}
How can I write the JSON data correctly to a file, if I have it in a JSONArray like services ?
The code, where I read the JSON data from the file (that works fine):
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
JSONObject jsonObject = (JSONObject) obj;
setMaxUsers((Long) jsonObject.get("maxUsers"));
setMaxTextLength((Long) jsonObject.get("maxTextLength"));
setMaxFileSize((Long) jsonObject.get("maxFileSize"));
// get all list of services
JSONArray serv = (JSONArray) jsonObject.get("services");
for (int i = 0; i < serv.size(); i++) {
JSONObject service = (JSONObject) serv.get(i);
Service servec = new Service();
servec.setServiceName((String) service.get("serviceName"));
servec.setClassName((String) service.get("className"));
servec.setIsEnabled((Boolean) service.get("isEnabled"));
services.add(i, servec);
}
The editing part is not yet written, so I call the writing part directly after the reading.
Have a look at the examples of JSON-simple.
It says here that you need to put the Objects one by one into the Array, using only primitive and String values. You may use Collections like Map that by themselves only contain String or primitive values.
JSONArray list = new JSONArray();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
StringWriter out = new StringWriter();
list.writeJSONString(out);
So, adding your Services is not allowed and won't work. You should add a toMap method in it where you convert it to a Map and fromMap to convert it back.
Like this (in Services.java):
public Map toMap() {
HashMap<String, String> serviceAsMap = new HashMap<>();
servicesAsMap.put("serviceName", serviceName);
servicesAsMap.put("className", this.class.getName() + ".class");
servicesAsMap.put("isEnabled", isEnabled);
// ... continue for all values
return servicesAsMap;
}
then you can use that Map to populate your JSONArray like this:
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i).toMap()); // use the toMap method here.
}
obj.put("services", servicesJSON);
Have a look at JSONArray Documentation.Here you will get list of methods available.This JSONArray is inherited from java.util.ArrayList,so we can use the methods available for ArrayList to JSONArray.
JSONArray userList = JSONFile.readJSONArray("users.json");
JSONArray newuserList = new JSONArray() ;
JSONObject jsonobject , newjsonObject;
for (int i = 0; i < userList.size(); i++) {
jsonobject = (JSONObject) userList.get(i);
String id = (String) jsonObject.get("id");
String pass = (String) jsonObject.get("password");
newuserList.add(jsonObject);
// Here we are putting json object into newuserList which is of JSONArray type
try{
FileWriter file = new FileWriter( "/users.json",false);
newuserList.writeJSONString(newuserList, file);
file.close();
}
catch(Exception e ){
e.getMessage();
}
Hope this will help !

How to put a List<class> into a JSONObject and then read that object?

I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.
If this were just a List<String> I could just do something like:
JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");
obj.put("list", sList);
Then I could traverse the list like:
JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
System.out.println(jArray.getString(ii));
The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();
//if List not empty
if (!sList.isEmpty()) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
}.getType();
String gsonString = new Gson().toJson(objList, collectionType);
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Just to update this thread, here is how to add a list (as a json array) into JSONObject.
Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

Categories