2

I have a very simple Object Array

Object[] args = new Object[] {"002"};

My goal is to JSON serialize this Object Array in Android and get the result as a byte array. There are two classes for JSON Serialization in Android. JSONArray and JSONObject. Which class should I use?

Spefically I am not sure how to use the

JSONObject json = new JSONObject();
json.put("key", "value");

routine in this case.

1 Answer 1

1

You should use a JSONArray for this

JSONArray jsonArray = new JSONArray();
jsonArray.put("002");
byte[] bytes = jsonArray.toString().getBytes()
Sign up to request clarification or add additional context in comments.

3 Comments

can I also do jsonArray.put(new Object[] {"002"}); would it have the same effect?
No, see the description on the value parameter here for the allowed arghements [linl](developer.android.com/reference/org/json/JSONArray.html#put(int, java.lang.Object))
You can however pass an Object array containing just boxed primitives or Strings as an argument to the constructor of JSONArray(). new JSONArray(new Object[]{"002"}).toString() would result in ["002"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.