How to extract JSON fields from an api - java

I have an api which returns data in the below format when i use the clientbuilder get():
final Response response = ClientBuilder.newClient().target("url").queryParam("CustomerQuery", jsonarr).request(MediaType.APPLICATION_JSON).get();
String actual = response.readEntity(String.class);
System.out.println(actual);
Result:
{"_id":{"timestamp":1649320244,"date":"2022-04-07T08:30:44.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:44.011+00:00"}],"MyDetails":{"Query":"query1^^","name":"NEH","address":"XXX","Format":"xml","Version":"2"}}
{"_id":{"timestamp":1649320255,"date":"2022-04-07T08:30:55.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:55.011+00:00"}],"MyDetails":{"Query":"query2^^^","name":"ABC","address":"YYY","Format":"xml","Version":"1"}}
I need to extract fields under MyDetails in the above string and i tried using :
final Response response = ClientBuilder.newClient().target("url").request(MediaType.APPLICATION_JSON).get();
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
System.out.println(jsonReader.readObject());
Please let me know how can i extract the fields.

If you have questions about how to use a JsonObject, read the Javadoc https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonObject o = jsonReader.readObject();
JsonObject details = o.getJsonObject("MyDetails");
// details.get...
Alternatively, use a different http client like Retrofit that encourages direct object mapping

There are many ways to do what you want to do. I will just describe some of them. You can use several Json parsing libraries. The most popular ones are Json-Jackson also known as faster XML (See link here). You can use method readValue of ObjectMapper class. For class parameter you can use Map.class or your custom written class that will reflect the structure of your Json.
Than there is Gson library, with its user guide
But also if you want a simplistic solution, I wrote my own open-source library that includes JsonUtils class that is a thin wrapper over Json-Jackson library that gives you a very simple solution. In your case it may look like this (assuming variable json is a String that contains your Json string):
try {
Map<String, Object>map = JsonUtils.readObjectFromJsonString(json, Map.class);
Map details = map.get("MyDetails");
} catch(IOException ioe) {
...
}
Map details will contain a map with all your keys and values from section "MyDetails". If you want to use this library here is where to get it: Its called MgntUtils and you can get it on Github with Javadoc and source code. It is available as maven artifacts as well. Here is a Javadoc for JsonUtils class

Related

Converting JSON file to string in RestAssured (Java)

I'm using IntelliJ to learn RestAssured; this is completely new territory for me. I have a simple .json file in place and I want to have a API Response to assert if it's the same as the mentioned .json file.
Basically: If the output of the call equals what I have in the json file, it's all good.
I used the demo restapi.demoqa.com for quick reference. This is what I have right now:
#Test
public void ComparewithJSONinResources()
{
String CityResponse = ?????
RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.request(Method.GET, "/Hyderabad");
String responseBody = response.getBody().asString();
System.out.println(responseBody);
Assert.assertTrue(responseBody.equals(CityResponse));
response.body();
}
I have the .json file in place called CityResponse.json. For easy reference, say on the location c:/CityResponse.
Is it possible to convert the Json file to a string to assert that the API and the JSON are equal?
Comparing JSON as String will never give accurate results, as you will possibly see inconsistency in space, tabs (indentation), property (key-value pair) sequencing etc. Your best bet is to parse JSON into POJO using one of the many popular libraries (Ex. Jackson, GSON etc). And this deserialization you need for both RestAssured Http response & one you are reading from .json file, and once you have two java objects, use standard Java comparision by overriding equals method.

Android - Accessing JSON children from a URL

I'm in the process of converting my website to an Android app and one of the pages' data currently is populated via JSON in my website. The way it works is that the URL generates a different JSON data with the same structure based on the passed ID. I already have the logic for passing the ID to the URL. Now I want to read the data through Java code and parse the JSON children and its values in it.
I have a URL that leads to the JSON file in textual form, but I'm not sure how to go about reading the data from it and accessing the child nodes based on the JSON key.
So I guess what I'm asking is what is the usual approach for this procedure? I see a lot of different examples, but none of which are applicable to my problem.
Anyone have any suggestions as to how I should approach this?
JSONObject = new JSONObject(yourjsonstring);
Now you have your Json Object...
If your Json start with array use this:
JSONArray = new JSONArray(yourjsonarray);
You can use existing libraries to parse JSON, gson or Moshi are two solutions.
The way you go about parsing the JSON is as followed
First you need to make pojo's with the same structure as the JSON file.
then you can parse it to java code via the fromJSON() method, this will make new objects and fill it with the data from the JSON.
gson example for clarification:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
where jsonLine = your json file and the Response.Class the pojo in which you want to json to load.
Now you have the JSON values as Java classes in response.
If you're using Retrofit and OkHTTP to perform the network calls i suggest you use Moshi as it's also from Square and claimed to work faster and better than gson. (if you want to know why you can leave a comment).
I think what you're trying to do is this
on post execute method do the following
#Override
protected void onPostExecute(String result) {
String status = "";
String message = "";
String tag = "";
String mail = "";
try {
JSONObject jsonResult = new JSONObject(result);
status = jsonResult.optString("status");
message = jsonResult.optString("message");
tag = jsonResult.optString("tag");
mail = jsonResult.optString("mail");
} catch (JSONException e) {
e.printStackTrace();
}
of course your json array contains different keys
Just reolace them with yours

Inject dynamically generated data into JSON

I have developed a tool that can test some requests to a server, the requests themselves are no more than some simple JSON files that are stored on the disc and can be added continuously, but ... there is one more thing, the JSON files contains an e-mail address that needs to be changed upon running the project each time, this is because each of users have a personal e-mail, I made that because server can't accept more than one request from an user. So I am looking for a solution to inject this e-mail address dynamically into JSON.
I'm using Java for this, and also jayway for REST API and Gson for JSONs. So far I looked into google, but can't find anything at all.
You could do this by these solutions:
Use json file as template string with markup like "{email: ${e-mail}}", then just use jsonTemplate.replace("${e-mail}", email[i])
parse json to Map or Object that model request, then change email field and build again json out of it
Use Gson.
Gson gson = new Gson();
String yourJsonInStringFormat = " {\"email\":placeHolder,\"password\":\"placeHolder\"}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);
This prints out:
{"email":"jose#com.com","password":"123456"}
The fields being injected do not need to be there already. For example this also works:
Gson gson = new Gson();
String yourJsonInStringFormat = "{}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

What is the JSP equivalent to json_encode ( in PHP )?

I am trying to encode a JSP servlet into JSON. What's the equivalent in JSP to json_encode() in PHP ?
JSP/Servlet isn't that high-level as PHP which has practically "anything built-in". In Java you've more freedom to choose from libraries. There are several JSON libraries in Java available which you can implement in your webapp, the popular ones being under each JSON.org, Jackson and Google Gson.
We use here Gson to our satisfaction. It has excellent support for parameterized collections and (nested) Javabeans. It's basically as simple as follows:
String json = new Gson().toJson(anyObject); // anyObject = List<Bean>, Map<K, Bean>, Bean, String, etc..
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Converting JSON to a fullworthy Javabean is also simple with Gson, see this example.
Gson is pretty cool.
Its almost the same as json_encode. Note that an encoded empty string in json_encodeevaluates to "\"\""
In Gson it returns ""
There is a list of several Java libraries that handle JSON encoding at the bottom of http://json.org/ — take your pick.
json_encode in php is similar to following package in java
dependency:
import com.fasterxml.jackson.databind.ObjectMapper;
code :
Map<Object,Object> dataArray = {some data in map}
ObjectMapper objMapper = new ObjectMapper();
String jsonString = objMapper.writeValueAsString(dataArray);
jsonString is if the final result like son_encode in php, which you can achieve with objectMapper class

Categories

Resources