简体   繁体   English

如何在控制器中将JSON格式的Java字符串转换为JSON对象

[英]How to convert json formated java string to json object in controller

All examples of converting string to json are of javascript. 将字符串转换为json的所有示例都是javascript。 mine is java class. 我的是java类。 So, i have a simple java string but formated in json. 因此,我有一个简单的Java字符串,但格式为json。 now i have recieved that from jquery post. 现在我已经从jquery post收到了。 now i have to convert that string into json object so that i can access the specific fields. 现在我必须将该字符串转换为json对象,以便我可以访问特定字段。

controller class 控制器类

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
    public void storeData(@RequestParam(value = "temp_str", required = false) String j_str, HttpServletRequest request) {


               // do the conversion and extraction of data from "j_str"


            }

j_str variable is recieveing this string j_str变量正在接收该字符串

{"temp_data":[{"temp_email":"roykumarsuraj@gmail.com","temp_pwd":"abc123"}]} {“ temp_data”:[{“ temp_email”:“ roykumarsuraj@gmail.com”,“ temp_pwd”:“ abc123”}]}

http://www.javacreed.com/simple-gson-example/ http://www.javacreed.com/simple-gson-example/

Gson gson = new GsonBuilder().create();
            Person p = gson.fromJson("your json string", Person.class);
            System.out.println(p);

you can use that libary to manage json objectos its very cool the Person.class is a java bean must have all properties you have in your string 您可以使用该库来管理json对象,它非常酷。Person.class是一个Java bean,必须具有字符串中具有的所有属性

If your Json string is extremely simple, you can just use: 如果您的Json字符串非常简单,则可以使用:

JSONObject jobj=new JSONObject(j_str);

Now you can access the JSON elements by: 现在,您可以通过以下方式访问JSON元素:

JSONArray jarr=jobj.getJSONArray('temp_data');
JSONObject jarr1=jarr.get(0);  // will contain {"temp_email":"roykumarsuraj@gmail.com","temp_pwd":"abc123"}

Now you can further access jarr1 similar to jobj. 现在,您可以进一步访问类似于jobj的jarr1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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