Как вы анализируете файл JSON и используете его для создания объекта класса? - PullRequest
0 голосов
/ 08 июня 2019

Я работал с файлами JSON, которые я мог использовать в своей программе.Тем не менее, я был немного смущен тем, как использовать библиотеку.Например, это следующий файл JSON, который я пытаюсь проанализировать здесь:

{
"shoes": [
    {
        "shoeName": "Shoe",
        "shoePrice": "120",
        "brand": "Shoe",
        "typeOfShoes": "Running",
        "style": "Cool",
        "Color": [
            "Blue",
            "Green",
            "Pink"
        ],
        "Sizes": [
            "W5/M3.5",
            "W5.5/M4"
        ],
        "Description": "The Shoe SE features sleek lines and a sheer upper that combine classic Air Max elements into a lightweight, comfortable and versatile icon. Together with its smart toe-down profile and extra lift, the shoe offers an ever-bigger expression..",
        "shipping": "0",
        "tax": "0",
        "sub-total": "0",
        "review": "4.5",
        "images": [
            "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto,b_rgb:f5f5f5/ds8ojj70wtpthbzadaft/air-max-dia-se-shoe-WCG8t5.jpg",
            "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto,b_rgb:f5f5f5,q_80/n5txnsyb21v5zhruxfer/air-max-dia-se-shoe-WCG8t5.jpg"
        ],
        "totalUsers": "60",
        "totalRaffles": "80",
        "clientID_Paypal": "",
        "clientSecret_Paypal": "",
        "isSold": "false"
    },
    {
        "shoeName": "Empty Shoe",
        "shoePrice": "",
        "brand": "",
        "typeOfShoes": "",
        "style": "",
        "Color": [
        ],
        "Sizes": [
        ],
        "Description": "",
        "shipping": "",
        "tax": "",
        "sub-total": "",
        "review": "",
        "images": [
        ],
        "totalUsers": "",
        "totalRaffles": "",
        "clientID_Paypal": "",
        "clientSecret_Paypal": "",
        "isSold": "false"
    },
    {
        "shoeName": "Empty Shoe1",
        "shoePrice": "",
        "brand": "",
        "typeOfShoes": "",
        "style": "",
        "Color": [
        ],
        "Sizes": [
        ],
        "Description": "",
        "shipping": "",
        "tax": "",
        "sub-total": "",
        "review": "",
        "images": [
        ],
        "totalUsers": "",
        "totalRaffles": "",
        "clientID_Paypal": "",
        "clientSecret_Paypal": "",
        "isSold": "false"
    }
]

}

Файл JSON полностью прост.Внутри есть массив объектов, называемых «ботинки», каждый из которых имеет свое собственное shoeName, shoePrice, бренд и т. Д. Однако, как я смогу создать массив объектов «Shoe», извлекая каждое из значений в файле JSON??

My Shoe.java:

import java.awt.Image;

public class Shoe {

    public int shoePrice;
    public int shipping;
    public int tax;
    public int subtotal;
    public int totalUsers;

    public double review;

    public int totalRaffles;
    public int rafflesBought;

    public String shoeName;
    public String style;
    public String typeOfShoes;
    public String brand;

    public Image[] images;

    public String name;
    public String description;
    public String[] colors;
    public String[] sizes;

    public boolean isSold;

    public Shoe(int shoePrice, int shipping, int tax, int subtotal, double review,

            int totalRaffles, int rafflesBought,

            String shoeName, String style, String typeOfShoes, String brand,

            Image[] images,

            String description, String[] colors, String[] sizes,

            boolean isSold) {

        this.shoePrice = shoePrice;
        this.shipping = shipping;
        this.tax = tax;
        this.subtotal = subtotal;
        this.review = review;
        this.totalRaffles = totalRaffles;
        this.rafflesBought = rafflesBought;
        this.sizes = sizes;
        this.shoeName = shoeName;
        this.style = style;
        this.typeOfShoes = typeOfShoes;
        this.images = images;
        this.description = description;
        this.colors = colors;
        this.isSold = isSold;
        this.brand = brand;

    }

}

Что я пробовал:

Я попытался определить массив Shoe и попытался его инициализироватьиспользуя цикл for для извлечения значений, создания Shoe и добавления его в массив, однако я не понимаю, как вы могли бы запрограммировать это.

1 Ответ

0 голосов
/ 08 июня 2019

Используйте библиотеку типа GSON для преобразования JSON в Object.

В pom.xml добавьте зависимость к GSON:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
 <version>2.8.5</version>
</dependency>

Поскольку ваш JSON возвращает String даже для целых и двойных чисел, это подходящее определение для вашего класса обуви.

public class Shoe
{
    public String shoeName;

    public String shoePrice;

    public String brand;

    public String typeOfShoes;

    public String style;

    public String[] Color;

    public String[] Sizes;

    public String Description;

    public String shipping;

    public String tax;

    public String subtotal;

    public String review;

    public String[] images;

    public String totalUsers;

    public String totalRaffles;

    public String clientID_Paypal;

    public String clientSecret_Paypal;

    public boolean isSold;

}

Так как 'shoes' - это объект родительского уровня, вам также необходимо определить его

public class Shoes
{

    private List<Shoe> shoes;


    public List<Shoe> getShoes()
    {
        return shoes;
    }

    public void setShoes(List<Shoe> shoes)
    {
        this.shoes = shoes;
    }
}

Предположим, jsonData - это вход JSON в виде строки, приведенный ниже код будет преобразованСтрока JSON для объекта "Shoes", который содержит List

Gson gson = new Gson();

Type dataType = (new TypeToken<Shoes>()
{
}).getType();

Shoes shoeList = gson.fromJson(jsonData, dataType);

for(Shoe e: shoeList.getShoes()) {
    System.out.println(e);
}
...