使用jsonbody请求将JSON转换为字符串/整型



你好,我试图使用post请求在请求体中拉入字符串和整数,最好的方法是什么?在rest客户机中输入如下内容,例如:

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

最新更新