Swagger UI + MVC 4 Web API Get JSON with object name - json

I am using swagger ui plugin to document my web api. I want to return JSON object like:
{"Person": {
"Id": 1,
"Name": "John",
"address": {
"Street": "ABC",
"City": "Penrith",
"PostCode": 2034,
"State": "NSW"
},
"DOB": "2013-11-11T00:00:00"
}
}
Notice the Person object name.
I can do this with the following code:
public HttpResponseMessage Get(int id)
{
Person person = new Person { Id = 1, Name = "John", DOB = new DateTime(2013, 11, 11), address = new Address { City = "Penrith", State = "NSW", PostCode = 2034, Street = "ABC" } } ;
return Request.CreateResponse(HttpStatusCode.Accepted, new { Person = person });
}
Unfortunately, because the return type is HttpResponseMessage and not Person itself, Swagger just shows model as HttResponseMessage. That's not what I want.
If I change the return type to Person and return a person object, I don't get the the Person object name in the JSON return. That returns only -
{
"Id": 1,
"Name": "John",
"address": {
"Street": "ABC",
"City": "Penrith",
"PostCode": 2034,
"State": "NSW"
},
"DOB": "2013-11-11T00:00:00"
}
Is there a way to return Person but have the JSON string with Person object name?

Simply create a new class which has a Person property, instance it, assign the value to the Person property and return this object.
In this way, the JSON will look as expected.
If you don't want to create a new class, try using an anonymous type, like this:
// If you have this object
var MyPerson = ...;
// Return this from Web API
return new { Person = MyPersons };
(I don't know if this last option will work for you)

Related

Rest Assured: extracting list of values from Json Response using java

I have a JSON Response and want to extract list of values from response for e.g all the values of id's present.
{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
{
"id": 4,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
"id": 5,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
"id": 6,
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}
]
}
I have tried below code but not able to achieve but it is only printing first value of id i.e 4.
public class Get_Request {
public static void main(String[] args) {
RestAssured.baseURI = "https://reqres.in/";
Response res = given()
.param("page", "2")
.when()
.get("/api/users")
.then()
.assertThat()
.contentType(ContentType.JSON)
.and()
.statusCode(200).extract().response();
/*String data = res.jsonPath().getString("data[0].first_name");
System.out.println(data);
*/
List<HashMap<String,Object>> allids = res.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("id");
System.out.println(a);
}
}
I am beginner in rest assured also i am not sure whether we can achieve the same. Any help would be appreciated. Thanks in advance.
Below Code will find all the ids present in the Response and it will print the result like 4 5 6
List<Integer> ids = res.jsonPath().getList("data.id");
for(Integer i:ids)
{
System.out.println(i);
}
That can be done by changing your path to data.id
List<Integer> ids = res.jsonPath().getList("data.id");
Integer id = ids.get(0);
You can use JsonPath wildcards to extracts data from response , which will save you from writing code everytime you have such requirement, use below JsonPath to extract list of Ids from your response :
$..id

How to access the variable in other test RESt Assured

I am new to REST Assured framework. I have written the below code. It's working fine.
private static String result;
#Test
public void getStudentById() {
Response response =
given().
header("authToken",userToken).
pathParam("SNum", "A123").
when().
get("/students/{SNum}").
then().
contentType(ContentType.JSON).
body("firstName",equalTo("JOHN")).
extract().
response();
result = response.print();
System.out.println("Response************************" + result);
}
#Test
public void StTest() {
System.out.println("Response************************" + result);
}
In the response I am getting JSON data
{"list":
[
{
"id": 0,
"SNum": "A123",
"title": "Mr",
"firstName": "JOHN",
"lastName": "Doe"
},
{
"id":1 ,
"SNum": "A12",
"title": "Mr",
"firstName": "James",
"lastName": "Pesr"
}
]
}
Here, I need id in second test. So I am printing result variable in second test but it is getting null. How to get the result variable in second test.
Use the following jsonPath to get id in the second test:
list[1].id
So you should be able to do:
int id = RestAssured.with(response.asString()).getInt("list[1].id");

Restangular - removing unwanted datas from json objects returned from server

I have created an restangular application which returns a Student object details json from the server, the application is working fine , but the problem is that it is returning student details with other unwanted datas along with it as shown below
Expected Json
{
"id": 1,
"firstName": "Alex",
"lastName": "Sam",
"age": 22
}
Actual Json
{
"id": 1,
"firstName": "Alex",
"lastName": "Sam",
"age": 22,
"route": "print",
"reqParams": null,
"$fromServer": true,
"parentResource": null,
"restangularCollection": false
}
script
var baseAccount = Restangular.one('print',"Alex");
baseAccount.get().then(function (account) {
console.log(JSON.stringify(account));
$scope.data = account; // Only one account
});
java
#GET
#Path("/print/{name}")
#Produces(MediaType.APPLICATION_JSON)
public Student produceJSON( #PathParam("name") String name ) {
Student st = new Student(name, "Sam",22,1);
return st;
}
Take in to account that this info is necessary if you want that Restangular provide services like update or delete this object through Rest services.
For removing this data you have to unrestangularize the object, it's done by stripRestangular().
var rawObject = Restangular.stripRestangular(restangularizedObject);

How to parse ObjectId (MongoDB) in JSON that is sent to Grails Server

I have searched many post here but I still couldn't find the answer yet.
Problem:
I want to parse this JSON:
{
"price": {
"currency": {
"class": "com.yintagoka.ad.Currency",
"id": {
"class": "org.bson.types.ObjectId",
"inc": -612166639,
"machine": -1775927134,
"new": false,
"time": 1393682821000,
"timeSecond": 1393682821
},
"code": "USD",
"longName": "United States Dollar",
"name": "USD",
"symbol": null
},
"amount": 100
},
"title": "title",
"description": "desc"
}
to become an Object in my Grails server
class House {
ObjectId id
String name
String title
Price price
// ... many more
}
class Price {
BigDecimal amount
Currency currency
}
class Currency {
ObjectId id
String code
String longName
String name
String symbol
}
Grails did almost all the heavy stuff for me, but it can't generate the ObjectId. So I will have Object Currency with all the property name filled with the value but the id will be null.
How can I tell Grails to render the ObjectId as well, preferably automatically.
Note: I don't want to use String for my id.
I also read a post that I can set it manually by request.JSON, but the problem is that I always get an empty map.
def save(House house) {
print('request = '+request.JSON)
print('house = '+house)
print('params = '+params)
}
out:
request = [:]
house = com.yintagoka.ad.House#217b1ead[id=<null>,title=title,description=desc,price=com.yintagoka.ad.Price#1a1b0107[amount=100,currency=com.yintagoka.ad.Currency#62e07ff4[id=<null>,name=USD,longName=United States Dollar,code=USD,symbol=<null>]]
params = [action:delete, controller:house]

JSON Array Parsing and Conversion to Java Types

I'm fairly new to programming, and I'm an intern working to develop a Blackberry App. So, I apologize in advance if I use any wrong terminology.
I make a HTTP Request for all of the friends of a particular user, and get a JSON response in this JSON array format.
{"users": [{"username": "jonbob", "first_name": "Jon", "last_name": "Bob", "phone": "5555555555", "full_name": "Jon Bob", "id": 1}, {"username": "joesmith", "first_name": "Joe", "last_name": "Smith", "phone": "5555555555", "full_name": "Joe Smith", "id": 2}]}
I'm using the org.json parsing library. I'm trying to create a Blackberry list containing all of the User's Friends (like an address book). But I am unsure how to acess the JSON Array with this org.json library. I want to create a Java Array with only the full_names of all the friends. How would you go about parsing this response to accomplish that?
Thanks
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
public class Foo
{
public static void main(String[] args) throws Exception
{
/*
{
"users": [
{
"username": "jonbob",
"first_name": "Jon",
"last_name": "Bob",
"phone": "5555555555",
"full_name": "Jon Bob",
"id": 1
},
{
"username": "joesmith",
"first_name": "Joe",
"last_name": "Smith",
"phone": "5555555555",
"full_name": "Joe Smith",
"id": 2
}
]
}
*/
String json = "{\"users\": [{\"username\": \"jonbob\", \"first_name\": \"Jon\", \"last_name\": \"Bob\", \"phone\": \"5555555555\", \"full_name\": \"Jon Bob\", \"id\": 1}, {\"username\": \"joesmith\", \"first_name\": \"Joe\", \"last_name\": \"Smith\", \"phone\": \"5555555555\", \"full_name\": \"Joe Smith\", \"id\": 2}]}";
JSONObject result = new JSONObject(json);
JSONArray users = result.getJSONArray("users");
int size = users.length();
Friend[] friends = new Friend[size];
for (int i = 0; i < size; i++)
{
JSONObject user = users.getJSONObject(i);
friends[i] = new Friend(user.getString("first_name"), user.getString("last_name"));
}
System.out.println(Arrays.toString(friends));
// output: [Jon Bob, Joe Smith]
}
}
class Friend
{
String firstName;
String lastName;
Friend (String f, String l) {firstName = f; lastName = l;}
#Override
public String toString() {return String.format("%s %s", firstName, lastName);}
}
You can have a look at GSon this library is powerful for json and java manipulation.
List<Users> users= gson.fromJson(json, new TypeToken<List<Users>>(){}.getType());
Here is the API doc.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html