Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion of array list to json object string

I have a model class method which returns a list of objects which contains all the registered user details. I want to fetch the list resturned by all() method and convert the data into JSON object and pass it to the view like a string. How can I do this conversion of this array list to JSON object?

I was unable to do this by below:

ObjectMapper mapper = new ObjectMapper();
JSONObject json = new JSONObject();
JsonNodeFactory jsonnode = JsonNodeFactory.instance;
ObjectNode result = new ObjectNode(jsonnode);
for (int i = 0; i < list.size(); i++) {
    json.put(list.get(i).fname, list.get(i));
    System.out.println(json.get("fname"));
}

@Entity
class Mydata extends Model {

    @Id
    public Long Id;
    public String fname;
    public String lname;
    public String city;
    public String state;
    /****************** READ/select OPERATION *****************/
    public static Finder < Long, Mydata > finder = new Finder(Long.class, Mydata.class);

    public static List < Mydata > all() {
        return finder.all();
    }
    public static void createuser(Mydata user) {
        user.save();
    }
}
like image 246
pret Avatar asked Jun 28 '13 07:06

pret


People also ask

How do I turn an array into a JSON object?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

Can we convert JSON array to string?

Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.

Can we convert ArrayList to string?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.

What is difference in [] and {} in JSON?

{} denote containers, [] denote arrays.


1 Answers

To convert ArrayList to Json, just download Open Source json utility from: http://json.org/java/ or Jar file from here

And just do:

JSONArray jsonAraay = new JSONArray(your_array_list);

That's it

Note: You should have setter/getter in your POJO/MODEL class to convert arraylist to json

like image 80
Rakesh Bhalani Avatar answered Oct 03 '22 07:10

Rakesh Bhalani