JSON 到 string/int 使用 jsonbody 请求的转换

JSON to string/int conversion using jsonbody request

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

{
    "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;

    } 

您可能需要考虑创建一个您想要的 class 并使用 gson 库将对象转换为 json。 我认为少 "dirty work".

会容易得多

在这里查看: 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);

    }
}