How can I get specific object from methods response JSON - java

I want to call another method if the condition is satisfied with the response of first method. But the response is in JSON and has many objects. I want to check if "RESPCODE" is "01" and if it is call a method.
Method:
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
if(inResponse.toString().equals("01")) {
CheckoutProcess();
} else {
Toast.makeText(getApplicationContext(), "Transaction Failed ", Toast.LENGTH_LONG).show();
Log.d("LOG", "Payment Transaction : " + inResponse);
}
}
Response:
TXNAMOUNT = 1000.00
PAYMENTMODE = PPI
CURRENCY = INR
TXNDATE = 2018-04-17 18:56:08.0
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Success
GATEWAYNAME = WALLET
BANKTXNID =
BANKNAME = WALLET

org.json library should be enough if it is only one or two properties you are interested in.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
int respcode = jsonObj.getInt("RESPCODE");
You can see a complete example here:
How to parse JSON in Java

Related

I want to make a request using OkHttpClient and I want to change the URL if the response is not successful

So I am requesting an API call to search records by phone number. If the response is unsuccessful, I want to change the URL to search the record by name. In order to send the request and obtain the response we have a try catch clause. My only thought would be to repeat the request and response using a new URL inside the original catch clause . Can anyone inform me how I should go about changing the URL and making a new request if the original request catches an exception. Here is my snippet of code that requests to search by phone number. And the stackstrace which is evident because the request fails.
OkHttpClient client = new OkHttpClient().newBuilder().build();
String phone = DNC_List[i].getNumber();
Request request = new Request.Builder().url("https://www.zohoapis.com/crm/v2/Leads/search?phone=" + phone)
.method("GET", null).addHeader("Authorization", "Zoho-oauthtoken 1000.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxx")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie",
"1a9a93sda653=12a340a9c5d3e8sfd2161d0b; crmcsr=43sdv9-07ads5-4549-a166-0aad54gw6b; _zcsr_tmp=435e5334fa5-4549-a1667s889s8cf6b; JSESSIONID=54FF23B98378EBB45E4FA411823B5E61")
.build();
System.out.println("request = " + request);
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println(i + "PrettyJson = " + prettyJsonString + "\n______________end of string________");
JSONArray jsonArray = (JSONArray) json.get("data");
JSONObject data0 = (JSONObject) jsonArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
String id2 = data0.getString("id");
DNC_ID[i] = id2;
System.out.println("DNC_ID[" + i + "]= " + DNC_ID[i]);
} catch (Exception e) {
// Need to search leads by name if phone number does not work
// How to change the URL to search by name
System.out.println("Entered catch clause: index = " + i);
e.printStackTrace();
}
Output for the failed code:
request = Request{method=GET, url=https://www.zohoapis.com/crm/v2/Leads/search?phone=1234567890, tags={}}
Entered catch clause: index = 0
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.App.main(App.java:103)
Your code is failing to parse some JSON it doesn't appear like it's necessarily because the search returned zero results. If that were true it would return an empty array. Double check your JSON shapes and make sure they match what the API returns.
Also, it appears like you are mixing and matching two different JSON libraries. The built in Android objects such as JSONObject and Google's GSON pick one and stick with one don't mix and match them.
To aid in debugging this use OkHttps built in logging system and experiment with setting different logger levels.
Also to help debug you can set up OkHttp debug logging with an interceptor.
Logger logger = LoggerFactory.getLogger(HttpUtil.class);
HttpLoggingInterceptor logging =
new HttpLoggingInterceptor((msg) -> {
logger.debug(msg);
});
logging.setLevel(Level.BODY);
client.addNetworkInterceptor(logging);

how to insert an array to JSONArray with rest assured

I want to insert the array with Rest Assured.
tokenUUIDs - is an array ( A variable that I defined in a previous step).
When I run the code - tokenUUIDs received a correct value But ArraytokenUUIDs have not received something good. He received : [[Ljava.lang.String;#6fc0bbc6]
This is my Method:
public static void releaseTokens(String[] tokenUUIDs )
{
try{
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject releaseTokens = new JSONObject();
releaseTokens.put("partnerCode", commonOps.partnerCode);
releaseTokens.put("apiAccessToken",commonOps.openAccessToken);
releaseTokens.put("sessionUUID",SessionUUID);
releaseTokens.put("taskUUID","TaskUUID");
JSONArray ArraytokenUUIDs = new JSONArray();
ArraytokenUUIDs.add(tokenUUIDs);
releaseTokens.put("tokenUUIDs", ArraytokenUUIDs);
request.body(releaseTokens.toJSONString());
Response response = request.post((getData("APIenv") + "/api/sessions/releaseTokens.php"));
int code = response.getStatusCode();
Assert.assertEquals(code, 200);
System.out.println("Status code for releaseTokens.php is" +code );
ResponseBody bodyreleaseTokens = response.getBody();
System.out.println("Body bodyreleaseTokens.php " + bodyreleaseTokens.asString() );
String statusbodyreleaseTokens = bodyreleaseTokens.asString();
String status = response.getBody().jsonPath().getString("status");
Assert.assertEquals(status, "OK");
test.log(LogStatus.PASS, "bodyreleaseTokens is done" );
}
catch (Exception e)
{
test.log(LogStatus.FAIL, "bodyreleaseTokens is not done");
test.log(LogStatus.FAIL, e.getMessage());
fail ("bodyreleaseTokens is not done");
}
Try to add every token individually
for (String s : tokenUUIDs){
ArraytokenUUIDs.add(s);
}
Change
ArraytokenUUIDs.add(tokenUUIDs);
to
for (String tokenUUID : tokenUUIDs) {
ArraytokenUUIDs.add(tokenUUID);
}
Also consider that variables in java are named with lowercase first letter as a standard to avoid confusion with classes.

java.lang.String cannot be converted to JSONObject where value already converted to JSONObject

It is a question that has been asked many times but i didn't find any solution from the answers that they gave.
Basically im using the GSON to create instances of classes to JSON in order to serialize them and store it into the cloud save.
Here is the code
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
User user = dbmanager.getUser();
String user_json = gson.toJson(user);
saved_data.put("user", user_json);
The dbmanager.getUser(); is an Sql query that collects the user from the android database and return it as an instance of the User class.
Then i'm using the load method to load the data
public void converLoadData(String data) throws ParseException
{
if (data == null || data.trim().equals("")) return;
try {
User user = new User();
data = data.replace("\\\\", "\\");
JSONObject obj = new JSONObject(data);
System.out.println("data: " + obj.toString());
JSONObject user_object = obj.getJSONObject("user");
System.out.println("user " + user_object.toString());
String last_sync = obj.getString("last_sync");
java.util.Date db_sync = dbmanager.getLastSync(user.getID());
}
catch (JSONException ex) {
ex.printStackTrace();
Log.e(TAG, "Save data has a syntax error: " + data, ex);
}
catch (NumberFormatException ex) {
ex.printStackTrace();
throw new RuntimeException("Save data has an invalid number in it: " + data, ex);
}
}
The return of the println of data is this one
data: {"current":"{\"title\":\"Puzzle
2\",\"fnMoves\":[],\"solution_path\":\"puzzles\/2\/CKqbKz5f\/7b1886a261b0400768e75dea91948576.json\",\"puzzlecolors\":[0,0,0],\"puzzle_path\":\"puzzles\/2\/CKqbKz5f\/41a0b30fdfdf6685dd50c6019391cc00.tmx\",\"level_id\":2,\"locked\":false,\"level\":2,\"puzzle_site_id\":2,\"id\":2,\"score\":20,\"fnkeys\":1,\"solved\":false,\"difficulty\":1.0}","solved":"[{\"id\":1,\"puzzle_id\":1,\"puzzle_tries\":10,\"user_id\":1}]","user":"{\"personphoto\":\"https:\/\/lh4.googleusercontent.com\/-5XfDNwK1PwI\/AAAAAAAAAAI\/AAAAAAAAPs8\/C0onA9lyKvY\/photo.jpg?sz=50\",\"google_id\":\"fdgsdfgfgfgsdgsdf\",\"personname\":\"Test
Test\",\"last_sync\":\"2014-08-18
22:12:12\",\"lifes\":3,\"highscore\":13,\"ID\":1}","last_sync":"2014-08-18
22:12:12"}
and here is the error. This error has to do with the data value because i have back slash? i'm passing the data (which is string) into a JSON object and then i'm trying to collect the user element. using this JSONObject user_object = obj.getJSONObject("user"); and this is where i\m having the error. Anyone who can help me please? thank you
org.json.JSONException: Value {"personphoto":"https://lh4.googleusercontent.com/-5XfDNwK1PwI/AAAAAAAAAAI/AAAAAAAAPs8/C0onA9lyKvY/photo.jpg?sz=50","google_id":"104757400111626678244","personname":"George Panayi","last_sync":"2014-08-18 22:12:12","lifes":3,"highscore":13,"ID":1} at user of type java.lang.String cannot be converted to JSONObject
Solution: I'm using "remove" method to remove extra backslashes and quotes which cause bad format of the JSON Object
data = data.replace("\\", "");
data = data.replace("\"{", "{");
data = data.replace("}\"", "}");
data = data.replace("\"[", "[");
data = data.replace("]\"", "]");
I was able to get it working by cleaning up the JSON object a bit. I think it's just a bad formatting error.
First, the escape slashes, they need to be uniform or removed. I removed the ones escaping the double quotes, but left them in everywhere else.
Then I removed the double quotes around the nested objects and arrays. "{...}" to {...} and "[...]" to [...]
Seems to be all that was necessary.
{"current":{"puzzle_path":"puzzles\/2\/CKqbKz5f\/41a0b30fdfdf6685dd50c6019391cc00.tmx","solved":false,"score":20,"difficulty":1,"level_id":2,"id":2,"fnkeys":1,"title":"Puzzle\n2","level":2,"solution_path":"puzzles\/2\/CKqbKz5f\/7b1886a261b0400768e75dea91948576.json","puzzlecolors":[0,0,0],"puzzle_site_id":2,"locked":false,"fnMoves":[]},"user":{"ID":1,"lifes":3,"google_id":"fdgsdfgfgfgsdgsdf","highscore":13,"last_sync":"2014-08-18\n22:12:12","personname":"Test\nTest","personphoto":"https:\/\/lh4.googleusercontent.com\/-5XfDNwK1PwI\/AAAAAAAAAAI\/AAAAAAAAPs8\/C0onA9lyKvY\/photo.jpg?sz=50"},"solved":[{"puzzle_id":1,"id":1,"user_id":1,"puzzle_tries":10}],"last_sync":"2014-08-18\n22:12:12"}

Parse Json In Java How to read Inner Value

Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);

Add More than 200 Test Cases to Test Set Using Java Rally Rest API

Using Following Code I am able to add test cases in to newly created test set in RALLY.
But it add only first 200 test cases from the Test case list.
private static String createTestSet(RallyRestApi restApi, String TSName, String points)throws IOException, URISyntaxException {
QueryRequest testcases = new QueryRequest("Test Case");
testcases.setFetch(new Fetch("FormattedID", "Name", "Owner","Test Folder"));
// All Test cases
testcases.setQueryFilter(new QueryFilter("TestFolder.Name", "=","testFolder").and(new QueryFilter("Method", "=", "Manual")));
testcases.setOrder("FormattedID ASC");
QueryResponse queryResponse = restApi.query(testcases);
JsonArray testCaseList = new JsonArray();
if (queryResponse.wasSuccessful()) {
System.out.println(String.format("\nTotal results: %d", queryResponse.getTotalResultCount()));
testCaseList=queryResponse.getResults().getAsJsonArray();
}else{
for (String err : queryResponse.getErrors()) {
System.err.println("\t" + err);
}
}
String ref = "null";
System.out.println("Creating TestSet: "+TSName);
try {
if(!testCaseList.isJsonNull()){
restApi.setApplicationName("PSN");
JsonObject newTS = new JsonObject();
newTS.addProperty("Name", TSName);
newTS.addProperty("PlanEstimate", points);
newTS.addProperty("Project", Project_ID);
newTS.addProperty("Release", Release_ID);
newTS.addProperty("Iteration", Iteration_ID);
newTS.add("TestCases", testCaseList);
CreateRequest createRequest = new CreateRequest("testset",newTS);
CreateResponse createResponse = restApi.create(createRequest);
ref = createResponse.getObject().get("_ref").getAsString();
}
} catch (Exception e) {
//System.out.println("Exception Caught: " + e.getMessage());
}
return ref;
}
Although the Total Result count of Test case query filter is greater than 200, Test Set is getting created with only 200 Test case in it.
#Brian's comment above is correct. By default RallyRestApi.query() will only return one page of data (with the default page size being 200). QueryResponse.getTotalResultCount() will return the total number of records that matched on the server. In order to get more than one page of data simply use QueryRequest.setLimit() first to set an upper bound on the number of results you'd like returned.

Categories