0

I need to convert a Vector<Vector<Float>> to a JSONArray. Apart from iterating through the vector and creating the JSONArray, is there any simpler way to do this?

Someone told me to try gson.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
ask
  • 2,160
  • 7
  • 31
  • 42
  • 1
    Why are you trying to serialize it and deserialize it in the same method? Your `json` string already holds your vector data as JSON. By trying to get a JSONArray you're trying to get it back into Java objects (but with a different JSON library). Why? Why not just use `data`? What are you actually trying to accomplish? – Mark Peters Aug 14 '12 at 14:49
  • My goal is to convert a Vector to a JSONObject. I searched around and it seemed like gson could help. Can you suggest a way to do this? – ask Aug 14 '12 at 15:19
  • Gson is for serializing Java objects into a JSON-formatted String. JSONObject however is a Java object which is used when you want to take a JSON-formatted String and translate it *back* to Java objects. It belongs to a completely different library. When I asked what you're actually trying to accomplish, I meant at a higher level since your current goal seems flawed. It doesn't make sense to go from one Java object type to another, using JSON as a pointless intermediary. Do you have code that takes a JSONObject or something? Are you trying to send JSON over a socket? What is your goal? – Mark Peters Aug 14 '12 at 15:24
  • Yes. I'm trying to store a Vector in SharedPreferences of Android. There's a post in this thread http://stackoverflow.com/questions/3876680/is-it-possible-to-add-an-array-or-object-to-sharedpreferences-on-android which takes a JSON object as a parameter to do this. I've already used Vectors throughout my code, so it's impractical to rewrite everything as a JSONArray. That's why I'm trying to convert a Vector to a JSONArray. – ask Aug 14 '12 at 15:45
  • 1
    There's a method `saveJSONObject` there working by converting the `JSONObject` to string. So unless I'm badly mistaken, you can skip the useless JSON part and simply save the string as suggested. – maaartinus Aug 14 '12 at 16:04

1 Answers1

1

SharedPreferences is just a key-value store. What's stopping you from bypassing JSONObject completely, and just using something like this (Gson only)?

private static final Type DATA_TYPE = 
    new TypeToken<Vector<Vector<Float>>>() {}.getType();

Storage:

Vector<Vector<Float>> data = new Vector<Vector<Float>>();
data.add(new Vector<Float>());
data.get(0).add(3.0f);

String dataAsJson = new Gson().toJson(data, DATA_TYPE);
sharedPreferences.edit().putString("data", dataAsJson).commit();

Retrieval:

String dataAsJson = sharedPreferences.getString("data", "[]");
Vector<Vector<Float>> data = new Gson().fromJson(dataAsJson, DATA_TYPE);

Disclaimer: I've never developed for Android.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190