java - 使用 jsonbody 请求将 JSON 转换为 string/int

标签 java web-services jax-rs

您好,我正在尝试使用发布请求来提取请求正文中的字符串和整数,最好的方法是什么? 在休息客户端中输入类似的内容,例如:

{
    "name":"ExName",
    "reading":"100"
}

@POST
    @Path("/SetFeeds")
    @Consumes(MediaType.APPLICATION_JSON)   
    @Produces(MediaType.APPLICATION_JSON) 
    @JsonCreator
    //public String setFeed(@PathParam("name")String name2, @QueryParam("name") String name,@Context UriInfo uriInfo,String jsonBody){
        public String setFeed(String jsonBody,@Context UriInfo uriInfo){        
            MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
            String query = uriInfo.getRequestUri().getQuery();
            String response = queryParams.getFirst("name");
            System.out.println(response);
            //System.out.println(name2);
            //JSONObject jsonObject = new JSONObject();
            //JSONObject nodeStats = name.get(getJSONObject("name"));
            // Getting the value of a attribute in a JSONObject
            //String sSDR = actualObj.getString("sdr");
            //FeedObjects x=new FeedObjects();
            //System.out.println(x.getName());


            return response;

    } 

最佳答案

您可能需要考虑创建一个您想要的类并使用 gson 库将对象转换为 json。 我认为“脏活儿”少了,事情就会容易得多。

在这里检查一下: https://github.com/google/gson

以下示例来自:http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {

    DataObject obj = new DataObject();
    Gson gson = new Gson();

    // convert java object to JSON format,
    // and returned as JSON formatted string
    String json = gson.toJson(obj);

    try {
        //write converted json data to a file named "file.json"
        FileWriter writer = new FileWriter("c:\\file.json");
        writer.write(json);
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(json);

    }
}

关于java - 使用 jsonbody 请求将 JSON 转换为 string/int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31989740/

相关文章:

web-services - WebServiceException:方法参数:<foo>不能为null。这是违反BP 1.1 R2211的行为

web-services - RESTful 是否会限制每个经过身份验证的用户角色的资源字段可见性?

java - Solr找不到库

java - 防止客户端/服务器应用程序上的数据篡改

java - 返回非持久数据作为对象的一部分

java - 遵循 Jersey 教程

java - 使用 JSON 作为 application/x-www-form-urlencoded

java - Selenium WB驱动程序: Verify text passes when the text is cut off?

java - 从 java web start 使用 CXF web 服务

java - 在 GAE 上运行 Glassfish JAX-RS 服务器无法正常工作