DataInputStream rd = new DataInputStream(request.getInputStream());
JsonObject json = new JsonObject();
上層代碼用於服務器。服務器得到一個inpustream,我想把這個流分配給JsonObject。 我如何將這個「rd」分配給「json」?如何將inpustream文件分配給json?
DataInputStream rd = new DataInputStream(request.getInputStream());
JsonObject json = new JsonObject();
上層代碼用於服務器。服務器得到一個inpustream,我想把這個流分配給JsonObject。 我如何將這個「rd」分配給「json」?如何將inpustream文件分配給json?
轉換輸入流,以串
public static String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (Exception e) {
Log.getStackTraceString(e);
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
流使用POJO類例如爲對象:
public class PageInfo {
private String pageName;
private String pageContent;
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getColorCode() {
return colorCode;
}
public void setColorCode(String colorCode) {
this.colorCode = colorCode;
}
}
映射類將字符串轉換爲對象
public Vector<PageInfo> getPageInfo(Cursor cursor) {
Vector<PageInfo> pageInfo = new Vector<PageInfo>();
// Column Index
int pageContent;
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
PageInfo info = new PageInfo();
pageContent = cursor.getColumnIndex(TablePageInfo.PAGE_CONTENT);
colorCode = cursor.getColumnIndex(TablePageInfo.COLOR_CODE);
bookMark = cursor.getColumnIndex(TablePageInfo.BOOK_MARK);
info.setPageContent(cursor.getString(pageContent));
pageInfo.add(info);
} while (cursor.moveToNext());
}
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return pageInfo;
}
添加GSON J AR然後寫下面的代碼會得到任何物體,並且將返回一個完美的JSON
package common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
//Generics is used so any class type can be passed
public class GsonSerializer<T> {
public T Deserialize(String json, Class classOfT) {
Gson gn = new GsonBuilder().create();
return (T) gn.fromJson(json, classOfT);
}
public String Serialize(T object) {
Gson gn = new GsonBuilder().create();
return gn.toJson(object);
}
}
更多的細節,你可以參考我的博客
http://lifeasanandroiddeveloper.blogspot.kr/2011/11/how-to-serialize-and-desearilize-json.html
你可以根據代碼 – Ranjith 2013-02-23 12:20:37
哪裏你'JsonObject'從何而來,GSON? – 2013-02-23 11:44:50
nop,它來自restfb(對於在api中使用的java) – 2013-02-23 11:49:42
將流轉換爲字符串和字符串 - >對象,使用GSON的對象,您可以輕鬆轉換json,如果它可以幫助你我可以發佈代碼 – Ranjith 2013-02-23 12:02:07