我在下面的代码中有一个名为'jo'的json对象。我将这个json对象转换为java字符串以将此json对象作为response返回。然后我如何将此字符串转换回所需格式的json对象。请帮助我
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*,java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%
JSONArray cellarray = new JSONArray();
JSONObject cellobj = null; //new JSONObject();
JSONObject jo=new JSONObject();
String country=request.getParameter("count");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/test","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from state
where countryid='"+country+"'");
while(rs.next()){
cellobj = new JSONObject();
cellobj.put("id", rs.getString(1));
cellobj.put("name", rs.getString(3));
cellarray.add(cellobj);
}
jo.put("arrayName",cellarray);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jo.toString());
}
catch(Exception e){
System.out.println(e);
}
%>
答案 0 :(得分:2)
你的问题似乎有些混乱+你的代码格式化也很混乱。但正如我所理解的,为了将String转换回JSONObject,你可以做到
String someString= getResponseFromServer();
JSONObject jsonObject = new JSONObject(someString);
// and then do with jsonObject variable whatever you desire
答案 1 :(得分:0)
使用代码:
String returnString = jo.toString();
并作为回复发送。
答案 2 :(得分:0)
答案 3 :(得分:0)
使用JSONObject
JSONObject jsonObj = new JSONObject("String");
答案 4 :(得分:0)
这应该可以解决问题
JSONObject jsonObject = JSONObject.fromObject(jo);
答案 5 :(得分:0)
// String to Json Object
JSONObject jsonObject = new JSONObject(stringResponse);
// JsonObject to String
String string = jsonObject.toString();
答案 6 :(得分:0)
无论您何时收到回复,都可以使用以下代码:
JSONObject json= new JSONObject ( responseString );
然后您可以处理与Json
对象相同的内容。
赞String id=json.put("id");
答案 7 :(得分:0)
这只是一个建议,我也面临着这个问题。
最后,我尝试使用GSON库。 GSON直接将您的JSONString转换为java类对象。
示例:
String jsonString = {"phoneNumber": "8888888888"}
创建一个新类:
class Phone {
@SerializedName("phoneNumber")
private String phoneNumebr;
public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}
public String getPhoneNumebr(){
return phoneNumber;
}
}
//在java中
Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);
System.out.println(" Phone number is "+phone.getPhoneNumebr());