How to retrieve a JSON array with android annotations? - java

I have a web service that sends a JSON similar to this one:
[
"4.11.3",
"4.10.7",
"4.10.2",
"4.9.1"
]
My Rest interface looks like this:
#Rest(...)
public interface RestInterface {
#Get("...")
String[] getVersions();
}
But I always get null as return value. Could someone help me please?

your json is a json-array of length 4 containing strings
so .... use following code :
JSONArray versionJsonArray=new JSONArray(<web-service response>);
String[] versionString=new String[versionJsonArray.length()];
for(int j=0;j<versionJsonArray.length();j++)
versionString[j]=versionJsonArray.getString(j);

Add this to your rest service:
#Accept(MediaType.APPLICATION_JSON)

Rest(...)
public interface RestInterface {
#Get("...")
JSONArray getVersions();
}
let the rest adapter type the string into a json array.

Related

Count the number of Arrays & access a specific array in the JSON Response using REST ASSURED with JAVA & Selenium

I am doing a POST call action through my selenium Automation program using Rest Assured API & Java. IO get a response as mentioned below-
{
"cmsContract": "HA1123",
"groupId": "12345",
"siteId": "4444-AP",
"stateCountyCode": "7978790"
},
{
"cmsContract": "HB2345",
"groupId": "9876",
"siteId": "8888-DK",
"stateCountyCode": "111225"
}
There are about 1000 or more JSON Objects in the response. And they don't have a identifier for the response like "name" or "contractinfo"
My query:
1. How do I retrieve the total count of the arrays (like one from '{' to '}') using Rest Assured APIs in conjuncture with JAVA and selenium?
If I had to retrieve 'stateCountyCode' for the result set with 'cmsContract' as HB2345 , how would I do that? I would want to see the value return as 111225
Please suggest.
Libraries used-
org.json.JSONObject;
io.restassured.RestAssured;
io.restassured.response.Response;
io.restassured.specification.RequestSpecification;
You can use JsonPath to parse JSON response. Basically, you can get JsonPath class from String, File or Response.
From String:
JsonPath path = JsonPath.from("json string");
From File:
JsonPath path = JsonPath.from(new File("path to file"));
From Response:
Response response; //we get it from RestAssured by calling POST/GET etc
JsonPath path = response.body().jsonPath();
In order to get any element in the JSON Structure, just like in your case, we have to provide it to JsonPath. Example JSON:
{
"data": [
{
"name": "test"
},
{
"name": "test1"
}
]
}
In order to access an element in the Array, we have to know ALL of its parents.
The structure looks like this:
path.get("parent.child.anotherChild");
The thing gets more tricky with Arrays because we have to use indexes.
The "data" in the example above is an array. In order to access test1 we would use:
path.get("data[1].name"); //second element in the array
But that's the standard approach. JsonPath is a much stronger library.
Finally, to answer your question. How do we get a count of JSON Objects in the Array?
List<HashMap<String, Object>> jsonObjects = path.getList("data"); //You have to provide name of the Array's parent. In my case, it's `data`
In the above List of HashMaps, we have ALL of JSON Objects in the JSON Array. So you can use multiple ways to count the elements.
To count how many JSON Objects there is you can simply use List's method:
jsonObjects.size();
With the same List, we can get cmsContract value, as in your example. We look for value HB2345.
Standard for loop. You can use Streams if you know how.
public String getStateCountryCodeFromCmsContract(String cmsContractValue) {
for (HashMap<String, Object> singleJsonObject : jsonObjects) {
String cmsContract = (String) singleJsonObject.get("cmsContract");
if (cmsContract.equals(cmsContractValue)) {
return (String) singleJsonObject.get("stateCountyCode");
}
}
}
We iterate over each JSON Object, check the value of cmsContract element, and if it equals the desired value - return stateCountryCode value.
Hope it helps!

How would I model a Gson object that can handle a dynamic field?

An API my application is communicating with sends responses that look like:
{
Code: 200,
Message: "HELLO",
Data: []
}
The Data field is always an array of SOMETHING. But that something could be a single node of text, another array of something else, or any other of an assortment of different objects.
In the below example, the data node is an array of an array of car objects.
Data: [ [ {car:1}, {car:2} ] ]
Another return type could be an array of insect objects:
Data: [ {insect : spider} ]
I would like to design a Gson object to handle this and was wondering what the best way would be.
My first thought is to have an abstract class that holds the Code and Message fields, and then have many sub-types that all have their own Data field. Then I would just call .fromJson() passing it the sub-class.
Is there a more optimal way to design it so that Gson would handle the differences?
I figured out what I believe is the best answer. Fairly straightforward!
Make the class generic and supply the type by creating a TypeToken before passing to Gson:
public class Response<T> {
private String code;
private String message;
private List<T> data;
}
Then when using Gson:
Type myCarListResponse = new TypeToken<Response<List<Car>>>(){}.getType();
Response<List<Car>> response = gson.fromJson(json, myCarListResponse);
Replace > with the type you are expecting from the Data node. The above example satisfies the first example from the original post.
To satisfy the second example:
Type myInsectResponse = new TypeToken<Response<Insect>>(){}.getType();
Response<Insect> response = gson.fromJson(json, myInsectResponse);
In Jackson, you can use #JsonAnyGetter/Setter to achieve this.
Refer http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html, http://wiki.fasterxml.com/JacksonFeatureAnyGetter

How can i get information from JSON dictionary in java

I have a dictionary on a website in form of json which looks for example like this:
"types":[{
"id":"0",
"name":"value1"
},{
"id":"1",
"name":"value2"
},{
"id":"2",
"name":"value3"
}]
I cant find any useful example of a method that could help me retrieve that information and put it in, for example, a string array.
Maybe anyone of you come across same problem please help!
P.S. I tried method like simplest way to read json from a URL in java with no success.
It is array of json object value whose key is types. You can use json-java library like gson, jackson,flexjson etc.. to parse this json object and achieve your required result.
GSON Example -
JsonElement jElement = new JsonParser().parse(jsonString);
JsonObject jObject = jElement.getAsJsonObject();
jObject = jObject.getAsJsonObject("types");
Or you can use pojo class like -
public class Type {
private int id;
private String name;
...
}
gson.fromJson(jsonString, Type.class);
Refer java docs.

Converting incoming JSON to Java array using Jersey

I have a REST api GET call that takes an array of strings formatted as JSON. I'd like to use Jersey to convert that array of strings to something like a string array or List. I've reviewed http://jersey.java.net/nonav/documentation/latest/json.html, but it looks like Jersey wants me to create an object that specifies how it should be mapped, which I really don't want to do because it's just a simple array.
#GET
public Response get(#QueryParam("json_items") String requestedItems) throws IOException
{
//Would like to convert requestedItems to an array of strings or list
}
I know there are lots of libraries for this - but I'd prefer to use Jersey and not introduce any new libraries.
Create a wrapper object for you data (in this case the Person class) and annotate it with #XMLRootElement
Your post method should look like this
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void post(List<Person> people) {
//notice no annotation on the method param
dao.putAll(people);
//do what you want with this method
//also best to return a Response obj and such
}
this is the right way to do this stuff where the data is sent in the request.
but if you want to have a QueryParam as the JSON data you can do this
say your request param looks like this:
String persons = "{\"person\":[{\"email\":\"asdasd#gmail.com\",\"name\":\"asdasd\"},{\"email\":\"Dan#gmail.com\",\"name\":\"Dan\"},{\"email\":\"Ion#gmail.com\",\"name\":\"dsadsa\"},{\"email\":\"Dan#gmail.com\",\"name\":\"ertert\"},{\"email\":\"Ion#gmail.com\",\"name\":\"Ion\"}]}";
you notice that its a JSONObject named "person" that contains a JSONArray of other JSONObjets of type Person with name an email :P
you can itterate over them like this:
try {
JSONObject request = new JSONObject(persons);
JSONArray arr = request.getJSONArray("person");
for(int i=0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o.getString("name"));
System.out.println(o.getString("email"));
}
} catch (JSONException ex) {
Logger.getLogger(JSONTest.class.getName()).log(Level.SEVERE, null, ex);
}
sry
Just try to add to your Response the array, like
return Response.ok(myArray).build();
and see what happen.
If it's just a very simple array it should be parsed without any problem.
EDIT:
If you want to receive it then just accept an array instead of a String. Try with a List or something like this.
Otherwise you can try to parse it using an ObjectMapper
mapper.readValue(string, List.class);

Playframework renderJSON() array

I'm using renderJSON() method to return an array of objects, with a custom JsonSerializer for the class of each element. The response has the following format:
[{"id":2,"name":"fred"},{...},...]
But I would like to add the name of the array at the begginning:
"arrayname":[{"id":2,"name":"fred"},{...},...]
How can I add the name of the object to a JSON response with renderJSON()? Should I use a template or can I do it with java code?
"arrayname":[{"id":2,"name":"fred"},{...},...]
looks like invalid Json, but if you wrap the array in an object you could get:
{"arrayname":[{"id":2,"name":"fred"},{...},...]}
E.g. something like this:
public class MyArrayWrapper {
public final User[] arrayname;
public MyArrayWrapper(User[] arrayname) {
this.arrayname = arrayname;
}
}
Then you can call renderJSON(new MyArrayWrapper(yourUserArray)); to get JSON like:
{"arrayname":[{"id":2,"name":"fred"},{...},...]}
Or just return as a list Arrays.asList(arr);

Categories

Resources