简体   繁体   English

将java字符串转换为json对象

[英]conversion of java string to json object

I have json object named 'jo' in the below code.I convert this json object to java string to return this json object as response.Then how i convert this string back to json object in the required format.Please help me. 我在下面的代码中有一个名为'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);
    }
%>

Your questions seems a bit messy + formating of your code is messy too. 你的问题似乎有些混乱+你的代码格式化也很混乱。 But as i understood you, in order to convert String back to JSONObject you can do 但正如我所理解的,为了将String转换回JSONObject,你可以做到

String someString= getResponseFromServer();
JSONObject jsonObject = new JSONObject(someString);
// and then do with jsonObject variable whatever you desire

Also as people sugested you can use java libraries such as GSON or JSONLib etc 此外,当人们消化时,您可以使用诸如GSONJSONLib等的Java库

use Code: 使用代码:

String returnString = jo.toString();

and send as response. 并作为回复发送。

You can use various libraries for this task - i recommend using GSON . 您可以使用各种库来完成此任务 - 我建议使用GSON You can find good tutorials on their site too, here . 你也可以在这里找到他们网站上的好教程。

I would use a custom object, not a simple JSONObject - you can deserialize and store your objects this way easily. 我会使用自定义对象,而不是简单的JSONObject - 您可以轻松地以这种方式反序列化和存储对象。

使用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();

Wherever you are receiving response , you can use the following code : 无论您何时收到回复,都可以使用以下代码:

 JSONObject json= new JSONObject ( responseString );

Then you can process the same as Json object . 然后你可以像Json对象一样处理它。

Like String id=json.put("id"); String id=json.put("id");

It is just a suggestion, I also faces like this issue. 这只是一个建议,我也面临着这个问题。

Finally, I tried with GSON library. 最后,我尝试了GSON库。 GSON is directly convert your JSONString to java class object. GSON直接将您的JSONString转换为java类对象。

Example: 例:

String jsonString = {"phoneNumber": "8888888888"}

create a new class: 创建一个新类:

class Phone {

@SerializedName("phoneNumber")
private String phoneNumebr;


public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}

public String getPhoneNumebr(){
return phoneNumber;
}

}

// in java //在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM