Convert String to array in android from json response - java

I am getting json response in array form like this
["Monday","Wednesday","Friday"]
, but it is not saving as a array in android, I am storing that in a string like this
String daysOfInterest = map.get("daysOfinterest");
[{"careTypeId":"10","careTypeName":"Vacation Care","daysOfinterest":["Tuesday","Thursday","Saturday"],"childDaysOfInterestId"‌​:"424"},
{"careTypeId":"10","careTypeName":"Vacation Care","daysOfinterest":["Monday","Wednesday","Friday"],"childDaysOfInterestId":"‌​425"}]
this is my response and I am storing that daysofInterest in hashmap...and getting using hashmap
But I want to get that in a array form

you can convert the json array into a java array with this
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] myArray = list.toArray(new String[list.size()]);
then you can pass the array elements to your map. more info here Convert Json Array to normal Java Array

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Days[] daysArray = gson.fromJson(jsonString, Days[].class);
Here is Gson library and here is example.

Hope this is useful.
yourstring is ["AA", "BB", "CC"]
if (!yourstring.equals("")) {
String[] type = yourstring
.replace("[", "")
.replace("]", "")
.replace("\"", "")
.split(",");
}

Related

How to remove extra escaping quote characters of JsonObject created through Javax

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Android parse Json array of Strings

How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

Convert normal Java Array or ArrayList to Json Array in android

Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?
If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
example key = "Name" value = "Xavier" and the value depends on number of array you pass in
try
{
JSONArray jArry=new JSONArray();
for (int i=0;i<3;i++)
{
JSONObject jObjd=new JSONObject();
jObjd.put("key", value);
jObjd.put("key", value);
jArry.put(jObjd);
}
Log.e("Test", jArry.toString());
}
catch(JSONException ex)
{
}
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
This is the correct syntax:
String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);
For a simple java String Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
My code to convert array to Json
Code
List<String>a = new ArrayList<String>();
a.add("so 1");
a.add("so 2");
a.add("so 3");
JSONArray jray = new JSONArray(a);
System.out.println(jray.toString());
output
["so 1","so 2","so 3"]
Convert ArrayList to JsonArray
: Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]

JSON formatted string to String Array

I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:
[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]
I now have a String that contains the JSON formatted string but need to convert it into two String arrays, one for name and one for id. Are there any quick paths to accomplishing this?
You can use the org.json library to convert your json string to a JSONArray which you can then iterate over.
For example:
String jsonString = "[[\"Air Fortress\",\"5639\"],[\"Altered Beast\",\"6091\"],[\"American Gladiators\",\"6024\"],[\"Bases Loaded II: Second Season\",\"5975\"],[\"Battle Tank\",\"5944\"]]";
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
JSONArray array = new JSONArray(jsonString);
for(int i = 0 ; i < array.length(); i++){
JSONArray subArray = (JSONArray)array.get(i);
String name = (String)subArray.get(0);
names.add(name);
String id = (String)subArray.get(1);
ids.add(id);
}
//to convert the lists to arrays
String[] nameArray = names.toArray(new String[0]);
String[] idArray = ids.toArray(new String[0]);
You can even use a regex to get the job done, although its much better to use a json library to parse json:
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
Pattern p = Pattern.compile("\"(.*?)\",\"(.*?)\"") ;
Matcher m = p.matcher(s);
while(m.find()){
names.add(m.group(1));
ids.add(m.group(2));
}

Categories

Resources