Forum Discussion

amarnath1234's avatar
amarnath1234
Contributor
6 years ago
Solved

how to get data using array concept

HI,

we have a client requirement to capture createtime,lastupdatetime,shortdescription,longdescription fields data for each Promotion from my response to a external source.so this Promotion depends upon configuration setting-its not like always 1 promotion, may be 2 or 3 for each request,depends upon the req/scnerio.below is my response.please suggest how to capture this all data by using Array concept.If 1 Promotion then i used that Datasource/sink concept and extract to my excel sheet but if more than1 promotion then this is not the right approch.

 

attached response for your references.

 

 

 

  • nmrao's avatar
    nmrao
    6 years ago
    amarnath1234,
    It would be appropriate to mark the solution which worked for you, not your reply.

11 Replies

  • avidCoder's avatar
    avidCoder
    Super Contributor

    Hey amarnath1234,

     

    If you are really good in handling JSON using Gson , jettison and json-simple, then it's quite easier for you to do it. You can use simple java code to handle this.

     

    1. Get the Json
    2. Convert to JSONArray of "personalizedOffers" and iterate using for loop till the size() of array.
    3. Convert the Array Data to JSONObject of "promotion" and again iterate using for loop till the "promotion" object size.
    4. Fetch all the String values you require, which exists inside promotion object.

    This is the way, you can handle this dynamically and you don't have to worry about the no. of "promotion" object existing.

     

    Here is the working code:-

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    import org.codehaus.jettison.json.JSONArray;
    import org.codehaus.jettison.json.JSONException;
    import org.codehaus.jettison.json.JSONObject;
    
    BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\json.txt"));
    		String json = "";
    		try {
    		    StringBuilder sb = new StringBuilder();
    		    String line = reader.readLine();
    
    		    while (line != null) {
    		        sb.append(line);
    		        sb.append("\n");
    		        line = reader.readLine();
    		    }
    		    json = sb.toString();
    		} finally {
    		    reader.close();
    		}
    		
    		JSONObject object = new JSONObject(json);
    		JSONArray personalizedOffers = new JSONArray(object.getString("personalizedOffers"));
    		for(int i=0; i<personalizedOffers.length(); i++) {
    			JSONObject validCoupon = (JSONObject) personalizedOffers.getJSONObject(i).get("validCoupon");
    			JSONObject promotion = validCoupon.getJSONObject("promotion");
    			System.out.println(promotion.getString("id"));
    			System.out.println(promotion.getString("createdTime"));
    			System.out.println(promotion.getString("lastUpdatedTime"));
    			System.out.println(promotion.getString("shortDescription"));
    			System.out.println(promotion.getString("longDescription"));
    }
    		

    If you are using ReadyAPI, please download - jettison.jar, put inside soapui/home/ext and then run this code.

     

    Please refer the link I have mentioned above. First take example of easy JSON and then try the JSON you have mentioned here.

     

    If the code works, please don't  forget to Accept as solution.

     

    Thanks,

    avidCoder

    • amarnath1234's avatar
      amarnath1234
      Contributor

      Hi Avidcoder,

      when i run this script i got 1 error message,script unable to findout this text file..

       

      which text file is this ?

      C:\\Users\\Desktop\\json.txt

       

      • avidCoder's avatar
        avidCoder
        Super Contributor

        That json.txt file contains response, which you had attached (res.txt) for the very first time you asked your question. You might be getting the response in ReadyAPI through APIs. You just need to remove the code where I have used to read the .txt file using StringBuilder and then run it.

         

        Here it is :-

        //Remove this code, since you are getting the response from ReadyAPI response tab. 
        BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\json.txt"));
        		String json = "";
        		try {
        		    StringBuilder sb = new StringBuilder();
        		    String line = reader.readLine();
        
        		    while (line != null) {
        		        sb.append(line);
        		        sb.append("\n");
        		        line = reader.readLine();
        		    }
        		    json = sb.toString();
        		} finally {
        		    reader.close();
        		}
        
        And into JSONObject, just pass the String JSON wwhich you are getting from ReadyAPI response tab.


         If it helps you out, Don't forget to give kudos or accept as solution.

    • amarnath1234's avatar
      amarnath1234
      Contributor

      when i run this script i got 1 error message,script unable to findout this text file..

       

      which text file is this ?

      C:\\Users\\Desktop\\json.txt

       

  • nmrao's avatar
    nmrao
    Champion Level 3
    /**
    * Below is script assertion
    * for the Rest Request test step
    * which reads json response
    * and extract user requested data
    * write into a csv file in system temporary directory
    **/
    def json = new groovy.json.JsonSlurper().parseText(context.response)
    def promotions = json.personalizedOffers*.validCoupon.promotion
    //You may add more columns if needed
    def columns = ['createdTime', 'lastUpdatedTime', 'shortDescription', 'longDescription']
    def sb = new StringBuffer()
    
    sb.append(columns.join(',')).append('\n')
    
    def buildPromotionData = { promotion ->
    	columns.eachWithIndex { key, index ->
    		promotion[key] ? sb.append(promotion[key]) : sb.append('')
    		(index+1 != columns.size()) ? sb.append(',')	: sb.append('\n')
    	}
    }
    
    promotions.each { buildPromotionData(it) }
    def file = "${System.getProperty('java.io.tmpdir')}/${System.currentTimeMillis()}.csv" as String
    log.info "Creating the file ${file}"
    new File(file).write(sb.toString())
    log.info sb.toString()
    
     

    The above  Script Assertion does what was requested. No additional libraries or test steps required.

    You may be able to open "CSV" file in excel if you want.

    • amarnath1234's avatar
      amarnath1234
      Contributor

      hi ,

       

      Thanks for your Help.

      with this code i got the data but I want to sink this data to excel sheet where other data are sinked as per my scnerio.how to sink this data to a excel sheet ?

      • nmrao's avatar
        nmrao
        Champion Level 3
        amarnath1234,

        But you got the idea from the above that how to extract the data from json response. May be you can start with it to put the data wherever you want to store.