Android-Java List to String and vice versa - java

I am new to Android programming and I wanted to create a function to take in a list and return a String. That's my code:
private String List_to_String(final ArrayList<String> list) {
String returnString = "{";
for (String _s : list) {
returnString = returnString + _s.replace(":","\\:") + ":";
}
if (returnString != null && returnString.length() > 0) {
returnString = returnString.substring(0,
returnString.length() - 1);
}
returnString = returnString.concat("}");
return returnString;
}
It works but now I want to make a function that returns a ArrayList when I give a String generated with the function above also I think you need to take extra care of the ":".
So if I have a String
HDJDJJDJ:JSJSJSJJSJS:SJJSHS\:\:JS
the function should return a list with these items
HDJDJJDJ
JSJSJSJJSJS
SJJSHS::JS
Can you understand me
Thanks for your help

Maybe you can try something like this.
In Android Studio
[File]->[Project Structure]->[Dependencies]->[Add Dependency]->[Library Dependency]-> choose 'app'(If you have multiple modules) -> search for 'GSON' -> choose implementation.
Initialize Gson in java class :
Private Gson gson = new Gson();
String to List :
List<T> myList = new ArrayList<T>();
String myString = gson.toJson(myList);
List to string :
Type myType = new TypeToken<List<T>>(){}.getType();
myList = gson.fromJson(myString, myType);

Related

How to store ArrayList into sharedPreferences in Android

In my application I want store ArrayList into sharedPreferences and get this list in another page!
For store this List i used this library : https://github.com/MrNouri/GoodPrefs
I write below codes, but when get this data I don't know how can get data!
My codes for store list :
for (int i : intList) {
stringBuilder.append("ID : ").append(testPlans.get(i).getId())
.append("Type : ").append(testPlans.get(i).getItemType())
.append("Content").append(steps.get(i).getStepData().toString()).append("-");
App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
testPlans.get(i).getItemType(),
steps.get(i).getStepData().toString()));
}
GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
My codes for get data :
private List<DataItem> storedStepsBodyList = new ArrayList<>();
Toast.makeText(context, ""+
GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
, Toast.LENGTH_SHORT).show();
This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)
But I don't know can i set default value for second item of constructor!
I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .
How can i fix it?
Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<Item> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = new Gson().fromJson(json, type);
return result;
}

How to convert Arraylist consisting of pojo class into array in java

I have a pojo class named "Performance" like this
public class Performance {
String productId;
String productBrand;
String productGraph;
//getters and setters
And I saved it to arraylist named "performanceList" like this:
JSONArray dataGraph=null;
JSONObject obj = new JSONObject(response);
dataGraph = obj.getJSONArray("product_list");
performanceList.clear();
for(int i=0;i<dataGraph.length(); i++){
JSONObject jsonObject = dataGraph.getJSONObject(i);
Performance performance = new Performance();
if(!jsonObject.isNull("id")){
performance.setProductId(jsonObject.getString("id"));
}
if(!jsonObject.isNull("brand")) {
performance.setProductBrand(jsonObject.getString("brand"));
}
if(!jsonObject.isNull("sales")){
performance.setProductGraph(jsonObject.getString("sales"));
}
performanceList.add(i, performance);
}
And now, can you please help me fetch the data from arraylist and be converted into array just like this
String []brand = {/*getProductBrand from arraylist*/};
String []id = {/*getProductId from arraylist*/};
String []id = {/*getProductGraph from arraylist*/};
Use foreach or for loop
String[] brand = new String[performanceList.size()];
for(int i=0;i<performanceList.size();i++)
{
brand[i] = performanceList.get(i).getBrand();
.....
......
}
Similary for other fields as well.
you could use stream.map() in java8
List<String> productBrands = performanceList
.stream()
.map(el-> el.getProductBrand())
.collect(Collectors.toList());
repeat same for el.getId() or any other data you need to collect from Performance objects

Convert list to array in java in another class

I have this code and I am new to this project so help me out this:
private List<DbParam> getCorrespondingDbParams(Map<String, Object> source, boolean continueOnKeyAbsent, CMetaBasicField...fields){
List<DbParam> dbParams = new ArrayList<>();
for (CMetaBasicField field : fields) {
String key = field.getKey();
if (!source.containsKey(key)) {
if(continueOnKeyAbsent){
continue;
} else {
return null;
}
}
dbParams.add(field.getDbParam(source.get(key)));
}
return dbParams;
}
and when dbParams go to getDbParam is type of List
default DbParam getDbParam(Object val) {
return new DbParam(new DbColumn(getDbField(), getFieldType()),val);
}
But I want to convert in array. How to do this?
I would recommend converting between an ArrayList and an array like this:
List<String> myArrayList = new ArrayList<String>();
String []myArray = new String[myArrayList.size()];
myArrayList.toArray(myArray);
You can convert a arraylist to an array by doing:
dbParam[] myArr= new dbParam[myList.size()];
myArr= myList.toArray(myArr);
so you should convert your list to arraylist
DbParam[] arr = list.toArray(new DbParam[list.size()]);

json.org Java: JSON array parsing bug [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have JSON object as follows:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
In Java I want to parse the above json object and store the values in an arraylist.
I am seeking some code through which I can achieve this.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
Thank you so much to #Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject while passing your string to JSONObject constructor as input
As JSONObject notation is represented by braces i.e {}
Where as JSONArray notation is represented by square brackets i.e []
3.) Retrieve JSONArray from JSONObject (created at 2nd step) using "interests" as index.
4.) Traverse JASONArray using loops upto the length of array provided by length() function
5.) Retrieve your JSONObjects from JSONArray using getJSONObject(index) function
6.) Fetch the data from JSONObject using index '"interestKey"'.
Note : JSON parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes (") like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key so in those cases when you are not sure about the presence of value so use optString, optInt, optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
From docs
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e "" if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
How to convert String to JSONObject in Java
Convert one array list item into multiple Items
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Performance
Ease of use (code is simple to write and legible) - that goes with features.
For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.

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"}]

Categories

Resources