JSON对象/数组Java类
我目前正在安卓 studio中为一个构造函数开发一个java类,其中的getter和setter试图使用JSON数组和对象。上面的代码示例是我的JSON数据格式,下面的代码是我的。JAVA类的方法,但我不确定数组哪里出了问题。我如何制作方法来添加成分(对象)、添加所有成分(数组)、获取一种成分(对象)和获取所有成分?(数组)
{"cocktails":[
{
"cocktail_name": "Apple Martini",
"cocktail_glass": "Martini",
"cocktail_ingredients": [
{
"amount": 37.5,
"measurement": "ml",
"ingredient": "Ketel One Vodka"
},
{
"amount": 12.5,
"measurement": "ml",
"ingredient": "Berentzen Apfel Korn"
},
{
"amount": 25,
"measurement": "ml",
"ingredient": "Apple Juice"
}
],
"cocktail_recipe": [
"first step",
"second step",
"third step"
],
"cocktail_description": "Nam ultrices, libero non mattis pulvinar, nulla pede ullamcorper augue, a suscipit nulla elit ac nulla. Sed vel enim sit amet nunc viverra dapibus. Nulla suscipit ligula in lacus.",
"cocktail_garnish": [
{
"amount": 1,
"measurement": "wedge",
"ingredient": "Apple"
}
],
"cocktail_alcoholic": true,
"cocktail_barware": ["bostin tin","bar spoon","strainer","match/lighter"],
"cocktail_tags": ["Green","Vodka","Martini","Medium","Ketel One", "Berentzen Apfel Korn", "Liquer", "Apple"],
"cocktail_img_id": "pic.jpeg",
"cocktail_video_id": "https://youtu.be/z4yL2xrI0RY"
}]}
public final class cocktail {
private String name;
private String glass;
private JSONArray ingredients; //this is now a json array
private String[] recipe;
private String description;
private JSONArray garnish; //this is a json array aswell
private Boolean alcoholic;
//private Float Abv;
private String[] barware;
private String[] tags;
private String image;
private String video;
// constructor
public cocktail(String name, String glass, JSONArray ingredients, String[] recipe, String description, JSONArray garnish, Boolean alcoholic, String[] barware, String[] tags, String image, String video) {
this.name = name;
this.glass = glass;
this.ingredients = ingredients;
this.recipe = recipe;
this.description = description;
this.garnish = garnish;
this.alcoholic = alcoholic;
//this.Abv = Abv;
this.barware = barware;
this.tags = tags;
this.image = image;
this.video = video;
}
//Get method for grabbing an ingredient from the ingredients list of "this" cocktail //change
public JSONObject getIngredient(String ingred) {
JSONArray ingred = this.ingredients;
ingredientObj = getJSONObject()
}
//Method for setting an ingredient of index i of "this" cocktail
public void setIngredient(Integer amount, String measurement, String ing) {
JSONObject ingredientObject = new JSONObject();
ingredientObject.put("amount",amount);
ingredientObject.put("measurement",measurement);
ingredientObject.put("ingredient",ing);
this.ingredients.add(ingredientObject);
}}
# 1 楼答案
下面是一个测试类和相应的代码。添加您正在考虑的其他字段应该相当简单。看起来大部分问题都是在JSON对象和常规Java类型之间的转换
对于这样的事情,您可能需要考虑使用一个像^ {A1}这样的库来从POJOs自动转换到JSON对象。
鸡尾酒测试。爪哇
鸡尾酒。爪哇