[英]conversion of java string to json object
我在下面的代码中有一个名为'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);
}
%>
使用代码:
String returnString = jo.toString();
并作为回复发送。
使用JSONObject
JSONObject jsonObj = new JSONObject("String");
这应该可以解决问题
JSONObject jsonObject = JSONObject.fromObject(jo);
// String to Json Object
JSONObject jsonObject = new JSONObject(stringResponse);
// JsonObject to String
String string = jsonObject.toString();
无论您何时收到回复,都可以使用以下代码:
JSONObject json= new JSONObject ( responseString );
然后你可以像Json
对象一样处理它。
像String id=json.put("id");
这只是一个建议,我也面临着这个问题。
最后,我尝试了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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.