Введите несколько данных вместе в форме, используя данные JSON
[
{
"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, я хочу ввести эти данные в одной форме, в которой мне нужно ввести itemNo и количество вместе. Как это можно сделать с помощью параметризации данных с помощью 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;
}
1 ответ
Это очень просто. Сначала создайте класс, скажем TestObject.java и Item.java следующим образом, чтобы приспособить вашу структуру json.
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();
}
}
}