Bharathi D
Bharathi D

Reputation: 1013

Convert to json string in Android

I am Having Contact class With firstname, lastname, phoneno, and Email properties.

How to do this... my Code:

 function Callback(result)
{
document.getElementById('res').innerHTML=result;
}

Upvotes: 0

Views: 990

Answers (2)

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

You want to convert information of a class into a JSON string? No problem- GSON will help you out.

In your case, you would have to do something like:

Gson gson = new Gson();
StringBuffer sb = new StringBuffer();

ArrayList<Contact> contact = new ArrayList<Contact>();
//add some contacts
....

for(Contact c : contact) {
     sb.append(gson.toJson(c));
}

String strToPass = sb.toString();

Upvotes: 1

Mehdi
Mehdi

Reputation: 1531

I suggest the Json Simple Library, you can easily map between JSON and Java Entities, in you case it can directly convert your Array List to a JSON Array ...

Example :

  LinkedList list = new LinkedList();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  String jsonText = JSONValue.toJSONString(list);
  System.out.print(jsonText);

Upvotes: 1

Related Questions