2016-11-04 4 views
1
[ 
{ 
    "name": "Test", 
    "type": "Private", 
    "item":[{"itmeNo":"PT-15003C","quantity":"3"}, 
      {"itmeNo":"PT-15003C","quantity":"3"}], 

    "successMsg":"Item(s) added to the job list." 
    } 
] 

안녕, 내 JSON 데이터를 json.Above입니다 사용하여 데이터의 파라미터를하고있는 중이 야 를 사용하는 형태로 함께 여러 데이터를 입력, 나는 함께 ITEMNO 및 수량을 입력 할 필요가있어서, 하나의 형식에서 데이터를 입력 할 . json을 사용하여 데이터 매개 변수화를 사용하여 어떻게 수행 할 수 있습니까? 하나의 키 - 값 쌍이있을 때 내 코드가 작동하지만이 경우 누군가 솔루션을 얻는 데 도움이 될 수 있습니까? 단일 키 쌍 값에 대해 다음 코드를 작성했습니다.는 JSON 데이터

public static Object[][] getData(String path) { 
    JSONParser parser = new JSONParser(); 
    JSONArray jArray = null; 
    Object[][] testData = null; 
    try { 
     jArray = (JSONArray) parser.parse(new FileReader(System.getProperty("user.dir") + path)); 
     testData = new Object[jArray.size()][1]; 
     Hashtable<String, String> table = new Hashtable<String, String>(); 
     int i = 0; 
     for (Object obj : jArray) { 
      table = new Hashtable<String, String>(); 
      JSONObject objJson = (JSONObject) obj; 
      Set<?> keys = objJson.keySet(); 
      Iterator a = keys.iterator(); 
      while (a.hasNext()) { 
       String key = (String) a.next(); 
       String value = (String) objJson.get(key); 
       // System.out.print("key : "+key); 
       // System.out.println(" value :"+value); 
       table.put(key, value); 
      } 
      testData[i][0] = table; 
      i++; 
     } 
     return testData; 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

가 귀하의 질문이 명확하지, 당신은 정확히 수행 할 작업을 취소하십시오 : 다음은 기초를 이해하는 데 도움이 될 것입니다 샘플 프로그램입니다. – Vickyexpert

+0

@ Niki : 이제는 여러 개의 개체가있는 "항목"배열에 갇혀있는 것처럼 보입니다. 그 경우라면 getJSONarray를 사용하고 "item"을 전달하고 배열의 수를 알고 나면 배열 내에서 객체를 반복 할 수 있습니다. – Max

+0

데이터 기반 테스트를 만들려고하십니까? 이 경우 TestNG를 [data-provider-extension] (https://github.com/cbeust/testng/wiki/3rd-party-extensions#data-provider-extension)과 함께 사용할 수 있습니다. – user861594

답변

1

매우 쉽습니다. 먼저 클래스를 작성하면 json 구조에 suite TestObject.javaItem.java을 다음과 같이 만들 수 있습니다. 다음과 같이

TestObject.java

import java.util.List; 

public class TestObject { 
    private String name; 
    private String type; 
    private List<Item> items; 
    private String successMsg; 

    /** 
    * @return the name 
    */ 
    public String getName() { 
     return name; 
    } 
    /** 
    * @param name the name to set 
    */ 
    public void setName(String name) { 
     this.name = name; 
    } 
    /** 
    * @return the type 
    */ 
    public String getType() { 
     return type; 
    } 
    /** 
    * @param type the type to set 
    */ 
    public void setType(String type) { 
     this.type = type; 
    } 
    /** 
    * @return the items 
    */ 
    public List<Item> getItems() { 
     return items; 
    } 
    /** 
    * @param items the items to set 
    */ 
    public void setItems(List<Item> items) { 
     this.items = items; 
    } 
    /** 
    * @return the successMsg 
    */ 
    public String getSuccessMsg() { 
     return successMsg; 
    } 
    /** 
    * @param successMsg the successMsg to set 
    */ 
    public void setSuccessMsg(String successMsg) { 
     this.successMsg = successMsg; 
    } 
} 

Item.java

public class Item { 
    private String itemNo; 
    private int qty; 

    /** 
    * @return the itemNo 
    */ 
    public String getItemNo() { 
     return itemNo; 
    } 
    /** 
    * @param itemNo the itemNo to set 
    */ 
    public void setItemNo(String itemNo) { 
     this.itemNo = itemNo; 
    } 
    /** 
    * @return the qty 
    */ 
    public int getQty() { 
     return qty; 
    } 
    /** 
    * @param qty the qty to set 
    */ 
    public void setQty(int qty) { 
     this.qty = qty; 
    } 

} 

는 이제 JSON 문자열을 구문 분석합니다.

Test.java

import java.util.ArrayList; 
import java.util.List; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

public class Test { 

    public static void main(String[] args) { 
     TestObject testObject = new TestObject(); 
     try { 
      JSONObject jsonObject = new JSONObject("{\"name\": \"Test\"," 
                + "\"type\": \"Private\"," 
                + "\"item\":[{\"itmeNo\":\"PT-15003C\",\"quantity\":\"3\"}," 
                + "   {\"itmeNo\":\"PT-15003C\",\"quantity\":\"3\"}]," 
                + "\"successMsg\":\"Item(s) added to the job list.\"}"); //pass json string 

      JSONArray jsonArray = jsonObject.getJSONArray("item"); //get the item jsonarray 

      testObject.setName(jsonObject.getString("name")); 
      testObject.setType(jsonObject.getString("type")); 

      List<Item> items = new ArrayList<>(); 
      Item item = null; 

      //Iterate the item array and add to the itemlist object 
      for (int i = 0; i < jsonArray.length() ; i++) { 
       JSONObject jsonItem = jsonArray.getJSONObject(i); 
       String itmeNo = jsonItem.getString("itmeNo"); 
       String quantity = jsonItem.getString("quantity"); 
       item = new Item(); 
       item.setItemNo(itmeNo); 
       item.setQty(Integer.parseInt(quantity)); 
       items.add(item); 
      } 

      testObject.setItems(items); 
      testObject.setSuccessMsg(jsonObject.getString("successMsg")); //Now you will have a testObject which have all values from json. 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 


}