简体   繁体   中英

Dynamic JSON passing to REST Web service and using it to insert data into mysql db

I am trying to pass a dynamic JSON string to my REST Web service which will in turn be used to populate a mysql db. I can do this using a hard-coded JSON string,however I dont know how to pass a dynamic JSON string.

How can I retrieve a parameter passed in via a WebService, parse it out as JSON, and persist that to the database?

Any insight is appreciated as I am very new to this topic. I am attaching my code which I have for the hard-coded JSON string parsing and adding to a mysql db.

My StackService.java

import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.google.gson.Gson;
import com.tracker.domain.Flow;
import com.tracker.persistence.HibernateUtil;
@Path("")
public class StackService {

    private Logger LOG = Logger.getLogger(StackService.class);



    /**
     * curl -X GET http://localhost:8080/stack
     */
    @GET
    @Path("")
    @Produces(MediaType.APPLICATION_JSON)
    public void getStock() {

        String stackJsonString = "{\"stack_name\":\"GOOG\",\"id\":null\"}";
        Gson gson = new Gson();
        Stack stock = gson.fromJson(stockJsonString, stock.class);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        String stockName = stock.getstock_name();
        stock.setstock_name(stockName);

        session.beginTransaction();
        session.save(stock);
        session.getTransaction().commit();


    }
}

if passing a json paramter is your problem, then u can try using the path parameter.

 @GET
    @Path("{jsonString}")
    @Produces(MediaType.APPLICATION_JSON)
    public void getStock(@PathParam("jsonString") String jsonString) {

        String stackJsonString = jsonString;

but i would recommend you to use post method which would make it simple but you should consider if it is an idempotent operation before u decide to use post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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