如何创建Json对象
问题描述:
我有像三个coloums(id(整数),startdate(文本),enddate(文本))的数据库。 我想读这些coloums的所有条目,将它们转换为Json并发送到web url。 我知道如何读取值,但不知道如何从这些值制作Json。 请任何编码帮助...如何创建Json对象
答
为什么你不试:
`
JSONObject object = new JSONObject();
try {
object.put("id", id);
object.put("startDate", startDate);
object.put("endDate", endDate);
} catch (JSONException e) {
e.printStackTrace();
}`
然后通过HTTP POST发送JSON对象
`
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}`
所以例如,如果你想创建一个包含所有你从一个SQLite得到三胞胎JSON对象分贝这将是:
String query = "SELECT *"+
"from "+TABLE_NAME;
Cursor c = db.rawQuery(query,new String[]{});
Log.d("query",query);
c.moveToFirst();
while(c.moveToNext()){
try {
int id = c.getInt(c.getColumnIndex("ID"));
String startDate = c.getString(c.getColumnIndex("START_DATE"));
String endDate = c.getString(c.getColumnIndex("END_DATE"));
object.put("id", id);
object.put("startDate", startDate);
object.put("endDate", endDate); }}
其中ID,START_DATE和END_DATE是数据库中字段的相应名称。
我无法测试我的代码,但现在我相信它的工作原理
答
下面是如何使一个JSON对象:
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", idValue);
jsonObject.put("startDate", endDateValue);
jsonObject.put("endDate", endDateValue);
您还可以通过执行获得JSON作为字符串:
jsonObject.toString();
答
JSONObject json = new JSONObject();
json.put("id", id);
json.put("startdate", startdate);
json.put("enddate", enddate);
答
使用杰克逊库,可以在地图或Java bean的转换成JSON字符串或生成一个JSON字符串的地图或JavaBean。你可能会写一个实用程序类:
public class JsonUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String convertToJsonStr(Object model) throws IOException {
return MAPPER.writeValueAsString(model);
}
@SuppressWarnings("unchecked")
public static Map<String, Object> readFromStr(String content) throws IOException {
return readFromStr(content, Map.class);
}
public static <T> T readFromStr(String content, Class<T> clazz) throws IOException {
return MAPPER.readValue(content, clazz);
}
}
这里是[文件](http://developer.android.com/reference/org/json/JSONObject.html);) – xiaowl 2012-08-01 08:22:22
当我环你的代码,是它为第二个条目创建新的Json对象...? – user1567965 2012-08-01 09:04:35
是的。由于存在“= new JSONObject();” – 2012-08-01 09:20:44