How to save JSON Array in SharedPreferences? [duplicate] - java

This question already has answers here:
Is it ok to save a JSON array in SharedPreferences?
(9 answers)
Closed 6 years ago.
I am new in Android. I want to save JSON Array in Shared Preferences.
Here is My Java Code:
while (managedCursor.moveToNext())
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("number", number);
jsonObject.put("type", type);
jsonObject.put("fDate", fDate);
jsonObject.put("duration", duration);
}
catch (Exception e)
{
e.printStackTrace();
}
jsonArray.put(jsonObject);
}
managedCursor.close();
Log.d("array", jsonArray.toString());

Firstly, I'd use Gson for converting json to/from Java objects,then can use something like following to store in SharedPreferences.
public void storeMyData(MyPojo myPojo) {
preferences.edit().putString(SOME_SHARED_PREF_KEY, gson.toJson(myPojo)).commit();
}
convert json to string and save to sharedpreference
preferences.edit().putString(SOME_SHARED_PREF_KEY,jsonobject.toString()).commit();
on reading from sharedPreference convert back to json by
String string = preferences.getString(SOME_SHARED_PREF_KEY, null);
JsonObject jsonObject = new JsonObject(string);

Related

How to convert a jsonArray into List<String> Java? [duplicate]

This question already has answers here:
Convert Json Array to normal Java list
(16 answers)
Closed 3 years ago.
I am using openjdk 11 and I am calling an api that is returning content type json. I parsing the response and converting into a string like this ( Need to do it this way as I am expecting responses in different formats/structure):
HttpEntity entity = response.getEntity();
try
{
responseBody = EntityUtils.toString( entity );
}
catch ( Exception e )
{
LOG.error( "Unable to parse response", e );
e.printStackTrace();
}
Where response is a org.apache.http.HttpResponse type object.
After converting into a string, the response looks like :
["abc","bcd","cde"]
Now, I was trying to put this into jsonObject or JsonArray as
JSONArray jsonArray = new JSONArray(responseBody);
Arrays.asList(jsonArray).stream().forEach(e-> LOG.info("Connector: " + e));
While my jsonArray looks good, getting error like :
["abc","bcd","cde"] is not an array
Question is : How to convert that jsonArray into a List in Java ?
I assume JSONArray comes from Android. You can just do 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());
}
}
Source: Convert Json Array to normal Java list

JSON Object cannot be converted to JSON Array [duplicate]

This question already has answers here:
org.json.JSONObject cannot be converted to JSONArray in android
(6 answers)
Closed 5 years ago.
I am getting this error when I am trying to convert following JSON response string from the server. I want to process JSONObject or JSONArray depending on the response from the server as most of the time it returns JSONArray.
JSON response from server
jsonString = {"message":"No Results found!","status":"false"}
Java code is as below
try
{
JSONArray jsonArrayResponse = new JSONArray(jsonString);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
if(jsonArrayResponse != null && jsonArrayResponse.length() > 0)
{
getCancelPurchase(jsonArrayResponse.toString());
}
}
}
catch(JSONException e)
{
e.printStackTrace();
}
Error Log:
org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
Can anybody help me.
Thanks
Based on your comment to answer 1, you can do is
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
Your response {"message":"No Results found!","status":"false"} is not an array. It is an object. Use JSONObject instead of JSONArray in your code.
TIP: Arrays are wrapped in square brackets[ ] and objects are wrapped in curly braces{}.
I fix this issue by writing following code [ courtesy #Optional ]
String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}";
/* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"},"
+ "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"},"
+ "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]";
*/
JSONArray jsonArrayResponse;
JSONObject jsonObject;
try {
Object json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
jsonObject = new JSONObject(jsonString);
if (jsonObject != null) {
System.out.println(jsonObject.toString());
}
} else if (json instanceof JSONArray) {
jsonArrayResponse = new JSONArray(jsonString);
if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) {
System.out.println(jsonArrayResponse.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Getting and saving JSON array from Socket.IO [duplicate]

This question already has answers here:
ArrayIndexOutOfBoundsException [closed]
(2 answers)
Closed 5 years ago.
Im get from my server an array of objects like this:
Log.i(TAG, "Destinos obtenidos: "+ destinosRuta);
Value of log -
Destinos obtenidos [{"Latitud":41.40404,"nombreDestino":"Barcelona","IDR":5,"IDD":6,"Longitud":2.168679},{"Latitud":37.408424,"nombreDestino":"Sevilla","IDR":5,"IDD":7,"Longitud":-5.9681},{"Latitud":38.92298,"nombreDestino":"Mérida","IDR":5,"IDD":4,"Longitud":-6.363121}]
which I want to stock on SharedPreferences, I have used the code from this answer:
putStringSet and getStringSet
But I don't know if i need to use an array of object, or I need to convert in an array of String, this is my code:
private Emitter.Listener onNuevaRuta = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String destinosRuta = "";
try {
destinosRuta = data.getString("destinosRuta");
}catch (JSONException e) {
return;
}
//destinosRuta has the previous value
ArrayList<String> listaDestinos = new ArrayList<String>(Arrays.asList(destinosRuta));
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
listaDestinos = getStringArrayPref(getApplicationContext(), "listaDestinos");
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0);
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
...
And, like the previous link, I have used his function:
public static void setStringArrayPref(Context context, String key, ArrayList<String> values) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray a = new JSONArray();
for (int i = 0; i < values.size(); i++) {
a.put(values.get(i));
}
if (!values.isEmpty()) {
editor.putString(key, a.toString());
} else {
editor.putString(key, null);
}
editor.commit();
}
public static ArrayList<String> getStringArrayPref(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(key, null);
ArrayList<String> destinos = new ArrayList<String>();
if (json != null) {
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
String destino = a.optString(i);
destinos.add(destino);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return destinos;
}
And i get an error when I'm tring to removed the first element of listaDestinos here:
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0); <--Error
FATAL EXCEPTION: main
Process: tfg.clienteandroid, PID: 17276
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.remove(ArrayList.java:403)
at tfg.clienteandroid.mapaActivity$3$1.run(mapaActivity.java:320)
Any idea? I want to remove twice and be able to use both objects from my array.
You don't need to store a list object. If you have your server already returning JSON, you can directly store that.
JSONObject data = (JSONObject) args[0];
String response = String.valueOf(data);
//... Or parse out the data you need
sharedPrefs.putString("response", response);
Convert the string into a JSON object or whatever on the way out and optionally parse it into actual Java objects (you can use Jackson or Gson to help you with that)
Anyway, not sure why you think you need to remove an object from a list in order to extract a value; besides, it looks like you only added one value to your list, not two. The Arrays.asList() method is creating you a list of one string. You can't remove two objects from that list
So, try to debug your code better with some breakpoints and more log statements.
In other words, you seem to have a problem parsing your data, not just using SharedPreferences
For example,
data.getString("destinosRuta");
Is that actually a string? Or an array? If an array, use the according method of the JSONObject class to get an array.
Save your json to preference like this
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
prefsEditor.putString("MyObject", destinosRuta);
prefsEditor.commit();
And get it when to use and convert to ArrayList or List as below
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
Type type = new TypeToken<List<Object>>(){}.getType();
List<Object> objects= gson.fromJson(json, type);

Finding Entries in JSON objects [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I've got this JSON in JSON object like this
JSONObject obj = new JSONObject(json);
I now want to get back "TRUE" (control F to find where that is)
{"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"Lorum","xmlns$openSearch":"Ipsum","xmlns$gsx":"Dolor","id":{"$t":"Lorum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Ipsum","term":"Dolar"}],"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"Lorum"},{"rel":"Ipsum","type":"application/atom+xml","href":"Dolor"},{"rel":"Lorum","type":"application/atom+xml","href":"Ipsum"},{"rel":"self","type":"application/atom+xml","href":"Dolor"}],"author":[{"name":{"$t":"spark"},"email":{"$t":"Lorum"}}],"openSearch$totalResults":{"$t":"1"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"Ipsum"},"updated":{"$t":"2016-07-30T07:40:03.369Z"},"category":[{"scheme":"Dolor","term":"Lorum"}],"title":{"type":"text","$t":"Ipsum"},"content":{"type":"text","$t":"parko2: TRUE"},"link":[{"rel":"self","type":"application/atom+xml","href":"Lorum"}],"gsx$parko1":{"$t":"TRUE"},"gsx$parko2":{"$t":"FALSE"},"gsx$indexfilteraanotisblankaarowsfilteraanotisblankaa":{"$t":""}}]}}
JSONObject obj = new JSONObject(json);
JSONObject obj1 =obj.getJsonObject("feed");
JsonArray array = obj1.getJsonArray("entry");
You will get array of entry array

Android Converting String to JSON [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need advice into how to work out a method in Android which has to pick a string loaded with JSON data and then convert it back to JSON.
For the time being, I have programmed the following but I'm not sure if I'm on the right track or not.
private void convert_JSON()
{
String json;
//funcions per a cridar el string amb JSON i convertir-lo de nou a JSON
JSONArray jsas = new JSONArray();
for (int i =0; i < jsas.length(); i++)
{
JSONObject message = jsas.getJSONObject(i);
String content = message.getString("content");
}
}
The JSON is loaded into a String in this other method:
private void read_JSON(String json)
{
JSONObject jObject = new JSONObject(json);
JSONArray jso3 = new JSONArray (jObject.getString("Nombres_Hijos"));
String name = jso3.getString("Nombre");
System.out.println(name);
String surname = jso3.getString("Apellidos");
System.out.println(surname);
int date = jso3.getInt("Año_nacimiento");
System.out.println(date);
JSONArray jsa2 = jso3.getJSONArray ("Nombres_Hijos");
String names = jsa2.toString();
for (int i=0; i < jsa2.length(); i++)
{
System.out.println(jsa2.getString(i));
}
jso3.toString(json);
}
And, lastly, the JSON is created within the MainActivity.java, not as a split file yet that does work correctly:
private void create_JSON(String json)
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jso.toString();
In short: what I want to know is if my method convert_JSON is on the right track or I'm misunderstanding how it's supposed to work like.
Thank you very much for your help.
Yours sincerely,
Mauro.
You can convert a jsonstring back to json using the following JSONObject(String json) constructor:
JSONObject jsonObject = new JSONObject(jsonString);
Just, put it inside a try catch block and you should be good to go :)
You can create a JSONObject from a String using the constructor:
JSONObject json = new JSONObject(myString);
And to convert your JSONObject to a String, just use the toString() method:
String myString = json.toString();
Additionally, if you are trying to get a specific String value from the JSONObject, you can do this:
if (json.has("content"))
{
String content = json.getString("content");
//do something with content string
}
Finally, if you aren't very comfortable using JSONObject, I recommend using the tools provided by droidQuery to help you parse, such as:
Object[] array = $.toArray(myJSONArray);
and
Map<String, ?> map = $.map(myJSONObject);
If you want a pure copy/paste example have a look here
Alternatively I would suggest using one of the many well documented libraries. My personal favourite is GSON
Plenty of examples on the net on how to use this.

Categories