Extracting text from Http response - java

following is the screenshot of http respone in java -
and following is the text form of response:
{
"LightGingerTheTextResult": [
{
"Confidence": 4,
"From": 0,
"LrnFrg": null,
"LrnFrgOrigIndxs": [],
"Mistakes": [
{
"CanAddToDict": false,
"From": 0,
"To": 0
}
],
"ShouldReplace": true,
"Suggestions": [
{
"LrnCatId": 12,
"Text": "An"
},
{
"LrnCatId": 45,
"Text": "A"
}
],
"To": 0,
"TopLrnCatId": 12,
"Type": 3,
"UXFrgFrom": 0,
"UXFrgTo": 6
}
]
}
I want to extract the "text" in the suggestion.
This is my part with json. I am getting final response in "finalResult"-
JSONObject json = new JSONObject();
try
{
StringBuffer response =urllib.urlopen(url);
String finalResponse= response.toString();
System.out.println("final response"+finalResponse);
StringBuffer result=(StringBuffer) json.get(finalResponse);
//finalResult=URLEncoder.encode(result.toString(), "UTF-8");
String finalResult=result.toString();
}
catch (Exception e) {
System.out.println(e.getMessage());
}

See stackoverflow.com/questions/2591098. You needs a library,
using package org.json with
new JSONObject(textOfResponse)
.getJSONArray("LightGingerTheTextResult").getJSONObject(0)
.getJSONArray("Suggestions").getJSONObject(0)
.getString("Text")
and your textOfResponse I get
An

If you are looking for a value of a specific JSON node you can use a JsonPath expression e.g. to extract values of all Text nodes:
$.LightGingerTheTextResult[*].Suggestions[*].Text
in your example simplifies to
$..Text
or just the first Text node from the first Suggestions node:
$.LightGingerTheTextResult[0].Suggestions[0].Text

I would suggest you to first start by retreive the body of your httpResponse object.
String tmp = response.body(); // I assume the callback method has a an
//argument of type
//httpResponse called response
Then store it somewhere eg:string.
Use gson and use the httpResponse class
like this:
httpResponse rep = gson.fromJson(, httpResponse .class);
This way you can now use the rep object to retreive what ever you want.

Related

Update Json value in json Array in Java

{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.

Not sure why it has to say not valid Json after replacing the values of paymentKey and Session key

I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.

Get all records from JSON response

I'm still kind of new to the Rest Assured API world. I've read through as much documentation on https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation as I can stand.
I have a response that looks like:
{
"StatusCode": 200,
"Result": [
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "Home",
"PhoneNumber": "9701234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile1",
"PhoneNumber": "2531234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile2",
"PhoneNumber": "8081234567",
}
]
}
I've been struggling with how to get just the first record's PhoneNumber.
String responseBody=
given()
.relaxedHTTPSValidation().contentType("application/json")
.param("api_key", api_key).
when()
.get("/api/employees/" + employeeId)
.andReturn().asString();
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result");
phoneNumber = jsonPath.getString("PhoneNumber");
I get all the phone numbers in this case:
phoneNumber = "[9701234567,2531234567,8081234567]"
How can I get just the first record? I'd rather not have to perform string operations to deal with the, "[".
Thanks
You can simply do,
JSONObject json = new JSONObject(responseBody);
phoneNumber = json.getJSONArray("Result").getJSONObject(0).getString("PhoneNumber");
Here, 0 indicates the first record in the JSON Array Result.
Because you know the index of the element you want to retrieve, you can use the following code:
JsonPath jsonPath = new JsonPath(response);
String phoneNumber = jsonPath.getString("Result[0].PhoneNumber");

GSON: MalformedJsonException when running the jar file (works fine in Eclipse)

This is my first post here, hope someone can help me on this because I can't understand what's wrong.
I have a java method that parses a JSON String
public static String getFieldFrom(String field, String event) {
try {
JsonElement jelement = new JsonParser().parse(event);
JsonObject obj = jelement.getAsJsonObject();
return obj.getAsJsonObject("from").get(field).getAsString();
}catch(Exception e) {
System.out.println("Error parsing field " + field + ": " + e);
}
return "-1";
}
Where the event is the string, and field the field I'm interested in. The program works fine when running on eclipse. If I compile it as a jar and I try to run it I get an Exception:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 3 path $
The JSON string that's being processed is the same, this one (looks valid to me):
{"event": "message", "id": "00000000b0a2a54e1a01000000000000d", "flags": 258, "fwd_from": {"id": "$01000000428d8006442ef91f3ed48e27", "peer_type": "user", "peer_id": 109088066, "print_name": "Sample_Name", "flags": 1, "first_name": "Name", "last_name": "Sample", "username": "sampleuser"}, "fwd_date": 1522850949, "from": {"id": "$050023200b0a234e82865474b11fd9cd", "peer_type": "channel", "peer_id": 123232323, "print_name": "ChnNameTest", "flags": 19609, "title": "ChnNameTest", "participants_count": 0, "admins_count": 0, "kicked_count": 0}, "to": {"id": "$011200000b0a2a54e812345674b47fd9cd", "peer_type": "channel", "peer_id": 1319412121236, "print_name": "ChnNameTest", "flags": 196609, "title": "ChnNameTest", "participants_count": 0, "admins_count": 0, "kicked_count": 0}, "out": true, "unread": false, "service": false, "date": 1522850949, "text": "This is the message text"}
I'm trying to get the "id" field, under "from" object. I've also tried with another library (org.json) but the behavior is the same. Again, if I run the code on eclipse it's working.
I really don't know what to try... Hope someone can help me!
Thank you!
UPDATE:
The problem seems to be related with the string passed. So this is the piece of code that reads the stdout of a script i'm calling (that sends back json text).
Process child = Runtime.getRuntime().exec(command);
InputStream in = child.getInputStream();
int c;
char ca;
String line="";
while ((c = in.read()) != -1) { //Read stdout char by char
ca=(char)c;
if(ca=='\n' || ca=='\r') { //Got a line
if(line.contains("{\"event\":")) {
System.out.println(getFieldFrom("id",line)));
}
line="";
}else {
line=line+ca;
}
}
in.close();
This is working for me.
String json="{\"event\": \"message\", \"id\": \"00000000b0a2a54e1a01000000000000d\", \"flags\": 258, \"fwd_from\": {\"id\": \"$01000000428d8006442ef91f3ed48e27\", \"peer_type\": \"user\", \"peer_id\": 109088066, \"print_name\": \"Sample_Name\", \"flags\": 1, \"first_name\": \"Name\", \"last_name\": \"Sample\", \"username\": \"sampleuser\"}, \"fwd_date\": 1522850949, \"from\": {\"id\": \"$050023200b0a234e82865474b11fd9cd\", \"peer_type\": \"channel\", \"peer_id\": 123232323, \"print_name\": \"ChnNameTest\", \"flags\": 19609, \"title\": \"ChnNameTest\", \"participants_count\": 0, \"admins_count\": 0, \"kicked_count\": 0}, \"to\": {\"id\": \"$011200000b0a2a54e812345674b47fd9cd\", \"peer_type\": \"channel\", \"peer_id\": 1319412121236, \"print_name\": \"ChnNameTest\", \"flags\": 196609, \"title\": \"ChnNameTest\", \"participants_count\": 0, \"admins_count\": 0, \"kicked_count\": 0}, \"out\": true, \"unread\": false, \"service\": false, \"date\": 1522850949, \"text\": \"This is the message text\"}";
Gson gson = new Gson();
JsonObject obj = gson.fromJson(json, JsonElement.class).getAsJsonObject();
String str = obj.getAsJsonObject("from").get("id").getAsString();
System.out.println(str);
Output:
$050023200b0a234e82865474b11fd9cd
Thanks #Nephilim !
Solved it by doing:
event=event.trim();
event=event.replace("[K","");
After event.trim(); the string has a "[K" at start which was not visible before. After removing that "[K" everything works!
It was probably some hiddend char that trim "extended".

Create a brand new type of searchable tree in JSON for Java

I am thinking of a new way to extract data from JSON. The following example is what I want:
Look for a key and value pair and give me that object.
Inside that object, give me the value to this key.
I want to get the power of knighthero in the following JSON, by telling it to find the username knighthero. This is really difficult, and I've tried JSONArray and JSONObject, but can't figure it out. I know the length is 3, but now what?
{
"data": [
{
"power": 75,
"registrant": {
"group": "elf",
"username": "kevin23"
}
},
{
"power": 34,
"registrant": {
"group": "fairy",
"username": "msi56"
}
},
{
"power": 150,
"registrant": {
"group": "orc",
"username": "knighthero"
}
}
]
}
I have tried JsonPath and all I get is [] when I print the string. I have tried JSONArray, but can't figure out how to do it.
With org.json librairy and your json described.
JSONObject jo0 = new JSONObject("{\"data\": ["
+ "{\"power\": 75,"
+ "\"registrant\": {\"group\": \"elf\",\"username\": \"kevin23\"}},"
+ "{\"power\": 34,"
+ "\"registrant\": {\"group\": \"fairy\",\"username\": \"msi56\"}},"
+ "{\"power\": 150,"
+ "\"registrant\": {\"group\": \"orc\",\"username\": \"knighthero\"}}"
+ "]}");
JSONArray ja = jo0.getJSONArray("data");
for(int i=0;i<ja.length();i++){
if(ja.getJSONObject(i).getJSONObject("registrant").getString("username").equals("knighthero")){
System.out.println(ja.getJSONObject(i).getInt("power"));
break;
}
}
EDIT
My bad, I make a mistake, here the good version

Categories