我已经使用gson将json解析为java对象。
Convert Json to Java Sample Code
现在我在eclispe面临堆内存问题,同样如下: Java heap space with GSON
正如我所说的gson-streaming文章那样
两者都讨论流式传输,
Gson流媒体处理速度快,但难以编码, 因为您需要处理处理JSON数据的每个细节。
我使用了客户端和通信对象。服务器通信。沟通结构就像
class CommunicationObject
{
//Other variables
IsBean isBean; //Interface of hibernate entity bean
//Getter & setter methods
}
这里isBean是访问任何单个实体bean时的通用。没有案例
->Do login logic then isBean has a user object
->Get organization then isBean has a Organization object.
...
etc
处理请求方法的代码:
public String processFacadeActionTest(String requestJson) {
Gson gson = new GsonBuilder().registerTypeAdapter(IsBean.class, new InterfaceAdapter<IsBean>())
.create();
CommunicationObject requestObj=null;
try{
requestObj=gson.fromJson(requestJson, CommunicationObject.class);
}catch (Exception e) {
e.printStackTrace();
}
FacadeActionHandler actionHandler=new FacadeActionHandler();
CommunicationObject responseObj = actionHandler.handleRequest(requestObj);
String returnString="";
try{
//TODO:Comment Bhumika heap space issue
returnString=convertIntoJson(responseObj);
return returnString;
}catch (Exception e) {
e.printStackTrace();
}
return returnString;
}
将对象转换为json
private String convertIntoJson(CommunicationObject obj) throws IOException
{
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(outputStream);
writeJsonStream(out, obj);
return outputStream.toString();
}
使用gson进行流式传输
private void writeJsonStream(OutputStream out,CommunicationObject communicationObject) throws IOException {
JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
writer.setIndent(" ");
writer.beginArray();
Gson gson = new GsonBuilder().registerTypeAdapter(IsBean.class, new InterfaceAdapter<IsBean>())
.create();
gson.toJson(communicationObject, CommunicationObject.class, writer); //Hear stuck how to map isBean object
writer.endArray();
writer.close();
}
我被困在 gson.toJson(communicationObject,CommunicationObject.class,writer) 如何在这样的请求对象上进行流式传输?或任何其他可用的替代品? 让我知道任何有问题的查询。