user733284
user733284

Reputation: 935

How to convert array of value objects to json?

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?

Upvotes: 1

Views: 408

Answers (1)

a.ch.
a.ch.

Reputation: 8380

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.

Upvotes: 5

Related Questions