有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    下面是一个测试类和相应的代码。添加您正在考虑的其他字段应该相当简单。看起来大部分问题都是在JSON对象和常规Java类型之间的转换

    对于这样的事情,您可能需要考虑使用一个像^ {A1}这样的库来从POJOs自动转换到JSON对象。

    鸡尾酒测试。爪哇

    import org.json.JSONArray;
    import org.json.JSONObject;
    import org.junit.Test;
    
    import static org.hamcrest.CoreMatchers.is;
    import static org.junit.Assert.assertThat;
    
    
    public class CocktailTest {
    
        @Test
        public void addOneIngredient() {
            Cocktail cocktail = new Cocktail();
            cocktail.addIngredient("whiskey", 5);
    
            assertThat(cocktail.root.toString(), is("{\"ingredients\":[{\"amount\":5,\"name\":\"whiskey\"}]}"));
    
        }
        @Test
        public void addTwoIngredients() {
            Cocktail cocktail = new Cocktail();
            cocktail.addIngredient("whiskey", 5);
            cocktail.addIngredient("olive", 2);
    
            assertThat(cocktail.root.toString(), is("{\"ingredients\":[{\"amount\":5,\"name\":\"whiskey\"},{\"amount\":2,\"name\":\"olive\"}]}"));
        }
    
        @Test
        public void getOneIngredient() {
            Cocktail cocktail = new Cocktail();
            cocktail.addIngredient("whiskey", 5);
            JSONObject ingredient = cocktail.getIngredient("whiskey");
    
            assertThat(ingredient.get("name"), is("whiskey"));
            assertThat(ingredient.get("amount"), is(5));
        }
    
        @Test
        public void getAllIngredients() {
            Cocktail cocktail = new Cocktail();
            cocktail.addIngredient("whiskey", 5);
            cocktail.addIngredient("olive", 2);
            JSONArray ingredients = cocktail.getIngredients();
    
            JSONObject whiskey = ingredients.getJSONObject(0);
            assertThat(whiskey.get("name"), is("whiskey"));
            assertThat(whiskey.get("amount"), is(5));
    
            JSONObject olive = ingredients.getJSONObject(1);
            assertThat(olive.get("name"), is("olive"));
            assertThat(olive.get("amount"), is(2));
        }
    }
    

    鸡尾酒。爪哇

    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class Cocktail {
        public final JSONObject root = new JSONObject();
    
        public Cocktail() {
           root.put("ingredients", new JSONArray()) ;
        }
    
        public void addIngredient(String ingredientName, int amount) {
    
            JSONObject ingredient = new JSONObject();
            ingredient.put("name", ingredientName);
            ingredient.put("amount", amount);
            JSONArray ingredients = (JSONArray) root.get("ingredients");
            ingredients.put(ingredient);
        }
    
        public JSONObject getIngredient(String ingredientName) {
            JSONArray ingredients = (JSONArray) root.get("ingredients");
            for (Object ingredientObj: ingredients ) {
                JSONObject ingredient = (JSONObject)ingredientObj;
                if (ingredient.get("name").equals(ingredientName)) {
                    return ingredient;
                }
            }
    
            throw new IllegalArgumentException("Couldn't find " + ingredientName);
        }
    
        public JSONArray getIngredients() {
            return root.getJSONArray("ingredients");
        }
    }