Разобрать файл JSON для объектов Java с помощью Gson - PullRequest
0 голосов
/ 05 декабря 2018

У меня проблемы с "преобразованием" данных в файле JSON в требуемые объекты Java.Файл JSON выглядит примерно так:

{
  "initialInventory": [
  {"bookTitle": "Harry Poter", "amount": 10, "price": 90},
  {"bookTitle": "The Hunger Games", "amount": 90, "price": 102}
  ],
  "initialResources":[
   {"vehicles":[
     {"license":123483, "speed": 2},
     {"license":999994, "speed": 4}
     ]
     }
    ],
  "services":{
    "time": {
      "speed": 1000,
      "duration": 24
    },
    "selling": 6,
    "inventoryService": 3,
    "logistics": 4,
    "resourcesService": 2,
    "customers": [
     {
        "id": 123456789,
        "name": "Bruria",
        "address": "NewYork 123",
        "distance":33,
        "creditCard":{"number":67890,"amount":88},
        "orderSchedule": [
            {"bookTitle": "Harry Poter", "tick": 3},
            {"bookTitle": "The Hunger Games", "tick": 3}
          ]
      },
    {
        "id": 234567891,
        "name": "Shraga",
        "address": "BeerSheva 3333",
        "distance":12,
         "creditCard":{"number":453536,"amount":220},
    "orderSchedule": [
        {"bookTitle": "The Hunger Games", "tick": 12}
    ]
    }
  ]
  }

Все файлы JSON, с которыми я буду иметь дело (пока), имеют одинаковую структуру.Я пытался использовать Gson для разбора файла (для этого мне нужно использовать Gson), я искал много видео и учебных пособий по этому вопросу, но большинство из них были слишком упрощенными или просто неактуальными, и кажется, что либослишком много способов сделать это, или я просто не могу понять, как это сделать правильно.

Это то, что я пробовал до сих пор:

public class BookStoreRunner {
    public static void main(String[] args) throws IOException { //has to be added, we get an error without it. can be dealt with try-catch, doesn't matter.

        Gson gson=new Gson();
        File jsonfile= new File("pathtofile"); //should be the actual path to the file.
        InputStream iStream= new FileInputStream(jsonfile);
        Reader reader = new InputStreamReader(iStream);
        JsonReader jsonReader =gson.newJsonReader(reader);
        JsonParser parser= new JsonParser();
        BookInventoryInfo[] books=gson.fromJson("initialInventory",BookInventoryInfo[].class);

        ResourcesHolder.getInstance().load(gson.fromJson("vehicles",DeliveryVehicle[].class));
        int timespeed= gson.fromJson("speed",int.class);
        int timeduration=gson.fromJson("duration",int.class);
        int numOfSellers=gson.fromJson("selling",int.class);
        int numOfInventories=gson.fromJson("inventoryService",int.class);
        int numOfLogistics=gson.fromJson("logistics",int.class);
        int numOfResourceServices=gson.fromJson("resourcesService",int.class);
        Customer[] customers=gson.fromJson("customers",Customer[].class);

          /* JsonElement jElement = parser.parse(reader); // JsonElement is equivalent to a list in java
        JsonObject jObject = jElement.getAsJsonObject(); //equivalent to an object of a class that implements the 'map' interface, e.g contains pairs of key:value
        JsonObject initialInventory = jObject.getAsJsonObject("initialInventory");
        JsonArray inventory =initialInventory.getAsJsonArray(); //it is an array (json syntax), but a JSONArray is not iterable.

       // dealing with inventory

        int i=0; //counter for all the books to be inserted to inventory array (index)
        for (Map.Entry<String,JsonElement> entry: initialInventory.entrySet()) //.entrySet() gives a set view of the JSONObject, which is iterable
        {

        }
        JsonArray iResources= jObject.getAsJsonArray("initialResources");
        JsonObject veh = iResources.get(0).getAsJsonObject();
        //initialization of java object, for the initialResources


        JsonObject services=jObject.getAsJsonObject("services");
        JsonObject timedata=jObject.getAsJsonObject("services").getAsJsonObject("time");
        int numOfSelling= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("selling"), int.class);
        int numOfInventories= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("inventoryService"), int.class);
        int numOfIogistics=gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("logistics"),int.class);
        int numOfResourceServices= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("resourcesService"),int.class);

        JsonArray jsonCustomers = jObject.getAsJsonObject("services").getAsJsonArray("customers");
        JsonObject jsonCustomersObject=jObject.getAsJsonObject("services").getAsJsonObject("customers");
        Customer[] customers = new Customer[5000]; // check if there's a problem with this part. unsure how many customers there are, or if we need\can use a list.
        int i=0; //customers index
        for (Map.Entry<String,JsonElement> entry: jsonCustomersObject.entrySet())
        {   //assuming we will implement a constructor for Customer which receives all the required values


        }

        */

Я пытался разобратьфайл с другим подходом, он отмечен как комментарий в конце кода.Я не могу понять, связана ли проблема с моим пониманием JSON в целом, с моим знанием использования ввода-вывода java или с тем, что я что-то упускаю.

Как эффективно создать нужные мне объекты из файла JSON с помощью Gson?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...