1

I have an array of classes of this type:

 public class IndexVO {
     public int myIndex;
     public String result;
 }

And this is my array:

     IndexVo[] myArray = { indexvo1, indexvo2 };

I want to convert this array to json, any idea how?

1 Answer 1

5

This wouldn't be as easy as JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray)) since your array contains objects of unsupported class. Hence you will have to make a little more effort:

JSONArray mJSONArray = new JSONArray();
for (int i = 0; i < myArray.length; i++)
    mJSONArray.put(myArray[i].toJSON());

And add toJSON() method to your IndexVo class:

public JSONObject toJSON() {
    JSONObject json = new JSONObject();
    ...
    //here you put necessary data to json object
    ...
    return json;
}

However, if you need to generate JSON for more than one class, then consider libraries which do it automatically, flexjson, for example.

Sign up to request clarification or add additional context in comments.

4 Comments

or override toString() method to return String.format("{\"myIndex\":\"%d\",\"result\":\"%s\"}", myIndex, restult);" and he can still use JSONArray mJSONArray = new JSONArray(Arrays.asList(myArray));
Yes, good idea. However, generally I use toString() for debug output purposes.
... and generally it will be less readable ... so if this is the only class that needs to be convert to json and project isn't large i'll go for override toString method ... for large project you're answer is better
what do u mean by here you put necessary data to json object , could u tell me more

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.