How to consume a json string from a rest service

Hello
Need some help with consuming a json  from my rest method...
This is my json
{
        "id": "8943207",
        "title": "clerk",
        "location": {
            "city": "miami",
            "stateCode": "fl",
            "stateName": "florida",
            "string": "ssssss"
        },
        "type": "Contract",
        "postingDate": "2015-07-01T06:52:07.01"
    }

Open in new window


public class FavService {

	@POST
	@Path("/user/{userId}/")
	@Produces(MediaType.TEXT_PLAIN)	
	public Response addFavorites(@PathParam("userId") String userId)
	{
	    // would like to get the value fron the json ... maybe in a Pojo
		return Response.status(200).entity("will add favorite for user= "+userId).build();
	}
}

Open in new window


Would like to call the rest service with the json string in the body and then capture the value...

Thanks for your help
chand pbAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
What JAX-RS implementation are you using?
chand pbAuthor Commented:
I am using FUSE.. but I think we using  jersey implementation,,, In addition, I plan to use the gson library

basically, I am hoping to create a java object

1: consume the json and save to DB
2: return an array of json from DB

But I need some help on how to create the beans with  for that json structure and consume it,,

Thanks for your help
mccarlIT Business Systems Analyst / Software DeveloperCommented:
So you may need to get a few more things working than just the below, but it is somewhere to start...

You need to create your model classes to align with your JSON structure. They should be plain java objects with the usual getter/setters (if required by YOUR code) with the field names aligned to the JSON names, something like...
public class User {
  private String id;
  private String title;
  private Location location;                // See Location definition below
  private String type;
  private String postingDate;

  public User() {}   // At least the Jackson mapping libraries need this, don't know about gson

  // Whatever other constructors, getters, setters that you need... (at least the below one for the service code to work
  public String getId() {
    return id;
  }
}

Open in new window


and

public class Location {
  private String city;
  private String stateCode;
  private String stateName;
  private String string;

  public Location() {}   // At least the Jackson mapping libraries need this, don't know about gson

  // Whatever other constructors, getters, setters that you need... 
}

Open in new window



And then in your service class you would have something like this...
public class FavService {

	@POST
	@Path("/user")
	@Produces(MediaType.TEXT_PLAIN)
	@Consumes(MediaType.APPLICATION_JSON)	
	public Response addFavorites(User user)
	{
		return Response.status(Status.OK).entity("will add favorite for user= " + user.getId()).build();
	}
}

Open in new window


Note: that since the id is passed at part of the JSON structure, you don't need the path param for it, just get it out of the resultant User object.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

chand pbAuthor Commented:
Thank you

 create the classes but I get
415 Unsupported Media Type and Response does not contain any data. When I tried it from advance rest client...

I will open another ticket for some help
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I noticed that you deleted your follow up question, does that mean that you resolved your issue?
chand pbAuthor Commented:
Thank you  mccarl for your help.. Yes, I deleted the question because i got it working but not like i wanted.. not able to map the  json to the  object in the method signature

so, I have  done the following

1: pass it in as json
2: collect it as string
3: using the gson class to map to the object



@POST
	@Path("/user/{userId}/")
	@Produces(MediaType.TEXT_PLAIN)
	@Consumes(MediaType.APPLICATION_JSON)	
	public Response addFavorites( String fav)
        {
                       Gson gson = new Gson();
		      Favorite favoriteObj = gson.fromJson(fav, Favorite.class);
         }

Open in new window


However, I can open a new question , if you saw the error  or has a solution where  I can  collect the  json as an object...

Thanks again for your help
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Ok, looking into it a bit more the reason is that Jersey doesn't know (by default) how to use Gson to work with the JSON strings. If you are not tied to Gson, you could try using Jackson which Jersey does not how to use out of the box, or otherwise you can write/use a Provider so that Jersey does know how to use Gson. The following link has some detail about a class that implements this Provider... http://eclipsesource.com/blogs/2012/11/02/integrating-gson-into-a-jax-rs-based-application/
chand pbAuthor Commented:
Not sure if this is correct.. but this is what I did... However, I will look in your suggestion but we are tied to using gson

@Path("/user/{userId}/")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public Response addFavorites(@PathParam("userId") String userId,String jobSummary) {
      Gson gson = new Gson();
     Favorite favoriteObj = gson.fromJson(jobSummary, Favorite.class);
}

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.