Inject dynamically generated data into JSON - java

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);

Related

How to extract JSON fields from an api

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

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

GSON to server in url format?

I have converted my java objects to json format.
InetAddress address = InetAddress.getByName("D****");
String ipAddress= address.getHostAddress();
Gson gson = new Gson();
String json = gson.toJson(ipAddress);
System.out.println();
I need to get the json value to server url format, eg: localhost:8080/json
so that I can get that value from the ajax url.
How can I achieve this?
I got it.
I used spring MVC to do this:
Here is the link

Simple JSON-String Query

I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.
My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.
Let's say my js object is
var obj={hero:"Spiderman",name:"Peter Parker"};
My Approach
1.Convert obj to JSON string and send
var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str);
2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string
3.Recieve and convert back to Json
var data= JSON.parse(xmlhttp.responseText);
I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.
It would be really helpful one could provide simple working code or point to some links where I can study.
P.S :
I cannot use Jquery as I am using AngularJS. See Why?
I will always send valid JSON string.
I can use other JSON lib. if its good than org.json and satisfy my needs.
Please provide its jar download link.
Assuming you are able to pull out data in your server code
This is how you can do it using org.json:
JSONParser parser = new JSONParser();
JSONObject requestObj = (JSONObject) parser.parse(data);
String name = (string)requestObj.get("name");
name = "Bruce Wayne";
Code to create the response can look something like this:
JSONObject response = new JSONObject();
response.put("name",name);
return response.toJSONString();
This assumes your server method returns a String type
And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
res.setContentType("application/json");
OutputStream os = res.getOutputStream();
os.write(response.toString().getBytes());
os.close();

How to access nested elements from a JSON using Java (Bing-Search-API)

I have this JSON that I retrieved using Bing-Search-API. Now, I'm not sure how to access the nested elements using GSON. I already made the source files for the JSON Structure Data.
If I do this:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonText).getAsJsonArray();
It is going to throw me that is not a JsonArray, so If I change it to JsonObject, how can I retrieve the String MediaUrl from Results.java?
Thank you
Based on the javadoc of Gson class:
Gson gson = new Gson();
Response response = gson.fromJson(jsonText, Response.class);
Results firstResult = response.getD().getResults().get(0);
System.out.println(firstResult.getMediaUrl());
So you don't need to use the JsonParser directly.
Your java classes have to be modified a little bit for this to work:
the type of results field in D.java has to be List<Results> so that Gson can find out the class of objects to populate with.
the naming of attributes/fields is inconsistent, some starts with lower case, others with uppercase. Make sure they are the same in the java classes and in the json string (considering case sensitivity). This issue might be addressed with using the appropriate FieldNamingStrategy for serialization/deserialization.

Categories

Resources