我有Contact类具有名字,姓氏,phoneno和电子邮件属性。转换为Android中的json字符串
- 我想将
ArrayList<Contact>
作为json字符串传递给网页(加载url)。
如何做到这一点...我 代码:
function Callback(result)
{
document.getElementById('res').innerHTML=result;
}
我有Contact类具有名字,姓氏,phoneno和电子邮件属性。转换为Android中的json字符串
ArrayList<Contact>
作为json字符串传递给网页(加载url)。如何做到这一点...我 代码:
function Callback(result)
{
document.getElementById('res').innerHTML=result;
}
你想一类的信息转换成JSON字符串?没问题 - GSON会帮助你。
在你的情况,你会做这样的事情:
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();
我建议Json Simple Library,你可以很容易地JSON和Java实体之间的映射,在你情况下,它的数组列表直接转换为JSON阵列...
例子:
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);
嗨..感谢..其工作wt我期望。 – RVG
没有GSON还有没有其他的选择吗? –
是的,你可以手动做到这一点,这是乏味的,特别是当你的课变得复杂时。 gson非常有用 - 它非常简单,非常轻便,并且由Google开发。你不会出错。 –
我从GSON下载jar文件。我不知道如何包含到我的项目中...... –