user2185851
user2185851

Reputation:

How to Use JSON Accumulate Method With List?

I am trying below code....

public  String listToJsonString(String keyName, List<StyleAttribute> attrs) {
        JSONObject json = new JSONObject();
        json.accumulate(keyName, attrs);
        return json.toString();
    }

But when i am checking json variable it contains empty values something like below

{"myKey":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}

And when i am checking attrs variables it contains 22 element Data.What i am doing Wrong here? I am just converting my List to Json Object and save to Database. I am using

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

Upvotes: 7

Views: 6623

Answers (2)

Subodh Joshi
Subodh Joshi

Reputation: 13512

You can use below code

public String listToJsonString(List<StyleAttribute> attrs) {
        JSONObject jObject = new JSONObject();
        try {
            JSONArray jArray = new JSONArray();
            for (MyClass myObject: attrs) {
                JSONObject styleJSON = new JSONObject();
                styleJSON.put("name",myObject.getName());
                styleJSON.put("rollNumber", myObject.getRollNumber());

                jArray.add(styleJSON);
            }
            jObject.put("keyName", jArray);
        } catch (Exception jse) {
        }

        return jObject.toString();
    }

It will resolve your issue.

Upvotes: 2

Padrus
Padrus

Reputation: 2078

Not sure on this one but maybe the objects in your List are serializable.

Also, what library do you use to manage JSON?

EDIT :

So json-lib it is!

I found this in the json-lib FAQ :

Json-lib creates empty JSONObjects from my bean class, help me!

Json-lib uses the JavaBeans convention to inspect your beans and create JSONObjects. If the properties of your beans do not adhere to the convention, the resulting JSONObject will be empty or half empty. You must provide a read/write method pair for each property.

Here's the wikipedia page talking about the JavaBeans conventions:

http://en.wikipedia.org/wiki/JavaBeans#JavaBean_conventions

Hope this will help you!

Upvotes: 1

Related Questions