如何将输入流文件分配给json?

时间:2013-02-23 11:38:38

标签: java json inputstream

DataInputStream rd = new DataInputStream(request.getInputStream());
JsonObject json = new JsonObject();

上层代码适用于服务器。服务器获取输入流,我希望将此流分配给JsonObject。 我如何将这个“rd”分配给“json”?

2 个答案:

答案 0 :(得分:1)

将输入流转换为字符串

    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;
}

}

将字符串转换为对象的Mapper类

 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 Jar然后编写下面的代码,它将获得任何对象,并将返回一个完美的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

答案 1 :(得分:0)

转换为String,然后转换为JSONObject

StringWriter writer = new StringWriter();
IOUtils.copy(request.getInputStream(), writer, encoding);
String theString = writer.toString();
JSONObject json = new JSONObject(theString);

有关IOUtils的详细信息,请查看here

要获取包含IOUtils类的jar,请查看here