JSON filtern nach bestimmten Wert

wofus

Mitglied
Hallo!

Ich habe von einer URL ein JSON das ich nach bestimmten Werten (eine bestimmte Tankstelle und der dazu gehörige Preis) filtern möchte. Die JSON sieht so aus:

JSON:
[
  {
    "id": 1473128,    "name": "Diskont Tankstelle",    "location": {
      "address": "Wien Breitenfurter Strasse 261 (\"Hofer-Parkplatz\")",      "postalCode": "1230",      "city": "Wien",      "latitude": 48.1506803,      "longitude": 16.3016662
    },    "contact": {
      "telephone": "43800202055",      "mail": "office@avanti.at",      "website": [URL='http://www.diskonttanken.at/']"http://www.diskonttanken.at/"[/URL]
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": true
    },    "paymentMethods": {
      "cash": false,      "debitCard": true,      "creditCard": true,      "others": "DKV-Card"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 1,    "open": true,    "distance": 1.348419844455978,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.081,        "label": "Super 95"
      }
    ]
  },   {
    "id": 1354799,    "name": "avanti - Vösendorf Schönbrunner Allee 20",    "location": {
      "address": "Schoenbrunner Allee 20",      "postalCode": "2331",      "city": "Voesendorf",      "latitude": 48.13078,      "longitude": 16.32632
    },    "contact": {
      "telephone": "800202055",      "fax": "800",      "website": "www.omv.com"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": true
    },    "paymentMethods": {
      "cash": false,      "debitCard": true,      "creditCard": true,      "others": "OMV STATIONSKARTE, DKV, MASTERCARD, MAESTRO, ROUTEX, DINERS, VISA"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 2,    "open": true,    "distance": 2.215112887233922,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.084,        "label": "Super 95"
      }
    ]
  },   {
    "id": 1354941,    "name": "avanti - Wien Edelsinnstraße 16",    "location": {
      "address": "Edelsinnstrasse 16",      "postalCode": "1120",      "city": "Wien",      "latitude": 48.1724,      "longitude": 16.31949
    },    "contact": {
      "telephone": "800202055",      "fax": "800",      "website": "www.omv.com"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": true
    },    "paymentMethods": {
      "cash": false,      "debitCard": true,      "creditCard": true,      "others": "OMV STATIONSKARTE, DKV, MASTERCARD, MAESTRO, ROUTEX, DINERS, VISA"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 3,    "open": true,    "distance": 2.4707759804019376,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.089,        "label": "Super 95"
      }
    ]
  },   {
    "id": 334,    "name": "OMV - Wien Sterngasse 13",    "location": {
      "address": "Sterngasse 13",      "postalCode": "1230",      "city": "Wien",      "latitude": 48.14891,      "longitude": 16.33836
    },    "contact": {
      "telephone": "16672130",      "fax": "16672133",      "mail": "retail.at.7666@omv.com",      "website": "www.omv.com"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": true,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "OMV STATIONSKARTE, DKV, OMV ROUTEX, MASTERCARD, MAESTRO, ROUTEX, DINERS, VISA, AMEX"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 4,    "open": true,    "distance": 1.3853832878526326,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.119,        "label": "Super 95"
      }
    ]
  },   {
    "id": 35755,    "name": "BP",    "location": {
      "address": "Triesterstrasse 104 ",      "postalCode": "1100",      "city": "Wien",      "latitude": 48.15715224,      "longitude": 16.34123557
    },    "contact": {
      "telephone": "4316674134",      "fax": "431667413416",      "mail": "R51876@bprosi.at"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "Routex"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "otherServiceOffers": "WildBean Cafe Shop Car Wash Servicehalle Reifenservice",    "position": 5,    "open": true,    "distance": 1.7694133390363103,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.119,        "label": "Super 95"
      }
    ]
  },   {
    "id": 35729,    "name": "BP",    "location": {
      "address": "Triesterstrasse 153 ",      "postalCode": "1100",      "city": "Wien",      "latitude": 48.15669974,      "longitude": 16.34239786
    },    "contact": {
      "telephone": "4316167464",      "fax": "431616746417",      "mail": "R51308@bprosi.at"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "Routex"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "otherServiceOffers": "WildBean Cafe Shop Car Wash",    "position": 6,    "open": true,    "distance": 1.826920331191898,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.119,        "label": "Super 95"
      }
    ]
  },   {
    "id": 1354920,    "name": "OMV - Wien Brunner Straße 77-79",    "location": {
      "address": "Brunner Strasse 77-79",      "postalCode": "1230",      "city": "Wien",      "latitude": 48.13342,      "longitude": 16.29849
    },    "contact": {
      "telephone": "18695856",      "fax": "1869585613",      "mail": "retail.at.7554@omv.com",      "website": "www.omv.com"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": true,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "UTA, DKV, OMV ROUTEX, MASTERCARD, MAESTRO, ROUTEX, DINERS, VISA, AMEX, OMV STATIONSKARTE"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 7,    "open": true,    "distance": 2.4487309885142343,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.119,        "label": "Super 95"
      }
    ]
  },   {
    "id": 35686,    "name": "BP",    "location": {
      "address": "Wienerbergstr. 29 ",      "postalCode": "1120",      "city": "Wien",      "latitude": 48.170951,      "longitude": 16.33682
    },    "contact": {
      "telephone": "4318156279",      "fax": "43181562793",      "mail": "R53132@bprosi.at"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "06:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "06:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "Routex"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "otherServiceOffers": "Waschstrasse MO - SA von 7-19 Uhr und SO von 9-15 Uhr",    "position": 8,    "open": true,    "distance": 2.6323166402600715,    "prices": [
      {
        "fuelType": "SUP",        "amount": 2.119,        "label": "Super 95"
      }
    ]
  },   {
    "id": 35768,    "name": "BP",    "location": {
      "address": "Altmannsdorferstr.117 ",      "postalCode": "1120",      "city": "Wien",      "latitude": 48.1609065,      "longitude": 16.3184664
    },    "contact": {
      "telephone": "4316678737",      "fax": "431667873713",      "mail": "R51022@bprosi.at"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "Routex"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 9,    "open": true,    "distance": 1.195593315320322,    "prices": []
  },   {
    "id": 35774,    "name": "BP",    "location": {
      "address": "Altmannsdorferstr.94 ",      "postalCode": "1120",      "city": "Wien",      "latitude": 48.1623607,      "longitude": 16.3172305
    },    "contact": {
      "telephone": "4318043718",      "fax": "43180437183",      "mail": "R51840@bprosi.at"
    },    "openingHours": [
      {
        "day": "MO",        "label": "Montag",        "order": 1,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DI",        "label": "Dienstag",        "order": 2,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "MI",        "label": "Mittwoch",        "order": 3,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "DO",        "label": "Donnerstag",        "order": 4,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FR",        "label": "Freitag",        "order": 5,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SA",        "label": "Samstag",        "order": 6,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "SO",        "label": "Sonntag",        "order": 7,        "from": "00:00",        "to": "24:00"
      },       {
        "day": "FE",        "label": "Feiertag",        "order": 8,        "from": "00:00",        "to": "24:00"
      }
    ],    "offerInformation": {
      "service": false,      "selfService": true,      "unattended": false
    },    "paymentMethods": {
      "cash": true,      "debitCard": true,      "creditCard": true,      "others": "Routex"
    },    "paymentArrangements": {
      "cooperative": false,      "clubCard": false
    },    "position": 10,    "open": true,    "distance": 1.3667554599840392,    "prices": []
  }
]
[B]
[/B]

Mein Code sieht ca so aus:

Java:
[/B]
import com.google.gson.Gson;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Rechner {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        
        Gson gson = new Gson();
        JSON.Root[] id = null;
        JSON.Price[] preis = null;

        String address = "https://api.e-control.at/sprit/1.0/search/gas-stations/by-address?latitude=48.150201766714105&longitude=16.319807691015892&fuelType=SUP&includeClosed=false";

        URL url = new URL(address);

        HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
        
        //httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
        
        InputStreamReader reader = new InputStreamReader(httpcon.getInputStream());
        
        id = gson.fromJson(reader, JSON.Root[].class);
        preis = gson.fromJson(reader, JSON.Price[].class);
        
        for (JSON.Root diskont : id) {
            
            System.out.println(diskont.id);       
        }

    }
}

Java:
[/B]
import java.util.ArrayList;

public class JSON {
    
    public class Contact{
        public String telephone;
        public String mail;
        public String website;
        public String fax;
    }

    public class Location{
        public String address;
        public String postalCode;
        public String city;
        public double latitude;
        public double longitude;
    }

    public class OfferInformation{
        public boolean service;
        public boolean selfService;
        public boolean unattended;
    }

    public class OpeningHour{
        public String day;
        public String label;
        public int order;
        public String from;
        public String myto;
    }

    public class PaymentArrangements{
        public boolean cooperative;
        public boolean clubCard;
    }

    public class PaymentMethods{
        public boolean cash;
        public boolean debitCard;
        public boolean creditCard;
        public String others;
    }

    public class Price{
        public String fuelType;
        public double amount;
        public String label;
    }

    public class Root{
        public int id;
        public String name;
        public Location location;
        public Contact contact;
        public OfferInformation offerInformation;
        public PaymentMethods paymentMethods;
        public PaymentArrangements paymentArrangements;
        public int position;
        public boolean myopen;
        public double distance;
        public String otherServiceOffers;
        public ArrayList<Price> prices;
    }



}[B][/B]


Wie komme ich an die ID einer einzelnen Tankstelle und dem dazugehörigen Preis? Ich bekomme leider nur alle IDs ohne Preise auf einmal ausgegeben.
 

wofus

Mitglied
So wie ich das sehe, sind die Preise sowieso immer ein leeres JSON-Array, wenn ich einfach das JSON aufrufe und mir angucke.
Kann sein das die Seite gerade aktualisiert wird. Passiert immer ab 12 Uhr. Normalerweise sind die ersten 5 Tankstellen mit Preisen angegben.

Aus der JSON interessiert mir der Wert "amount":

JSON:
"prices": [
      {
        "fuelType": "SUP",        "amount": 2.094,        "label": "Super 95"
      }
 

httpdigest

Top Contributor
Eine Möglichkeit wäre, z.B. per gson das JSON in Java-POJOs zu mappen, z.B. so:
Java:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
public class JsonTest {
  public static class Preis {
    public double amount;
    public String toString() {
      return "{amount=" + amount + '}';
    }
  }
  public static class Tankstelle {
    public String id;
    public List<Preis> prices;
    public String toString() {
      return "{id='" + id + '\'' + ", prices=" + prices + '}';
    }
  }
  public static void main(String[] args) throws Exception {
    List<Tankstelle> tankstellen = new Gson().fromJson(new InputStreamReader(new URL(
            "https://api.e-control.at/sprit/1.0/search/gas-stations/by-address?" +
                    "latitude=48.150201766714105&" +
                    "longitude=16.319807691015892&" +
                    "fuelType=SUP&" +
                    "includeClosed=false"
    ).openConnection().getInputStream()), new TypeToken<List<Tankstelle>>() {}.getType());
    System.out.println(tankstellen);
  }
}
Hierzu brauchst du: https://mvnrepository.com/artifact/com.google.code.gson/gson/2.9.0
 

httpdigest

Top Contributor
Aber: Wieso sagst du, du willst nach bestimmten Werten filtern können? Du meinst wohl eher projizieren?
Du willst ja nicht z.B. nur jene Tankstellen listen, bei denen bestimmte Kriterien erfüllt sind, also z.B. Preis kleiner als oder größer als ein Limit? Also bestimmte Tankstellen komplett wegfiltern.
Sondern du willst nur bestimmte Attribute aus dem gesamten JSON pro JSON-Array-Element projizieren. Also, du willst alle JSON-Array-Elemente (Tankstellen) haben und davon nur die id und price Werte. Das nennt man dann nicht filtern sondern projizieren (wenn man jetzt mal aus der SQL-Welt kommt).
 

wofus

Mitglied
Danke, das klappt schonmal zum Teil :)

Achso das wusste ich nicht. Wieder was gelernt. Eigentlich schon. Ich möchte nur eine bestimmte und zwar immer dieselbe Tankstelle beobachten ob der Preis steigt oder sinkt.

Gibt es die Möglichkeit nach einer bestimmten ID im JSON Dokument zu suchen und alle unteren Verzweigungen (zB.: Preise, Öffnungszeiten, ... ) aus zu lesen?
 

KonradN

Super-Moderator
Mitarbeiter
Also im Augenblick verstehe ich hier noch ein paar Dinge nicht. Du bekommst ja ein Json zurück, das ein Array mit Elementen hat. Diese Elemente haben unter anderem auch ein Element prices.

Wieso versuchst Du da zwei Mal etwas einzulesen?

Java:
        id = gson.fromJson(reader, JSON.Root[].class);
        preis = gson.fromJson(reader, JSON.Price[].class);

Die erste Zeile sollte ja bereits ein Array mit den ganzen Elementen beinhalten incl. den Preisen. Also da einfach mal rein schauen.

Dann dein JSON Klassenkonstrukt: Die inneren Klassen haben so ja eine Bindung an die äußere Klasse. Da wundert es mich etwas, dass dies so funktioniert. Hat da Gson wirklich Instanzen von erzeugen können? Die inneren Klassen müssten doch alle static sein, damit dann Instanzen davon erzeugt werden können. Aber wozu auch die innere Klassen? Da wäre doch einfach ein Namespace mit diesen Klassen angebrachter, oder?

Und wenn man dies so behoben hat, dann sollte es möglich sein, das Array durchzugehen um damit zu machen, was immer Du willst. Da kann man dann mit einfachen Schleifen heran gehen oder das auch gerne als Stream verarbeiten.

Wie komme ich an die ID einer einzelnen Tankstelle und dem dazugehörigen Preis? Ich bekomme leider nur alle IDs ohne Preise auf einmal ausgegeben.
Das ist ja auch klar - du gibst ja auch nichts anderes als die id aus.

Schauen wir uns einfach die Daten einmal an:
Deine Root Klasse hat id und eine ArrayLIst prices. Also wäre da etwas denkbar wie:

Java:
        for (JSON.Root diskont : id) {
            for (JSON.Price price : id.prices) {
                System.out.println(diskont.id + ", " + price.amount);
            }
        }

(Ich hoffe, ich habe die einzelnen Feldnamen und so richtig geschrieben.)

Und da kannst DU dann natürlich auch beliebige Abfragen einbauen und so (Unabhängig von irgend einem wording).

Aber evtl. habe ich das eigentliche Problem auch gar nicht verstanden.
 

KonradN

Super-Moderator
Mitarbeiter
Nur um kurz aufzuzeigen, wie sowas aussehen könnte:
  • Ich habe einmal die Daten abgefragt und als Datei hinterlegt
  • Die JSON Inneren Klassen sind bei mir in einem Namespace gelandet.

Den folgenden Test habe ich mal aufgebaut - die Entity ist jetzt nur eine innere Klasse geworden - das wäre in einem Projekt natürlich eine äußere Klasse.

Java:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import de.kneitzel.json.Root;
import org.junit.jupiter.api.Test;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FuelPriceReaderTests {

    public static class PriceInfo {
        int id;
        double amount = Double.NaN;

        public PriceInfo(Root root) {
            id = root.id;
            if (!root.prices.isEmpty()) amount = root.prices.get(0).amount;
        }
    }

    @Test
    public void testFuewlPriceREader() {
        Gson gson = new Gson();
        TypeToken<ArrayList<Root>> token = new TypeToken<ArrayList<Root>>() {};
        ArrayList<Root> fuelData = gson.fromJson(new InputStreamReader(getClass().getResourceAsStream("./fuelprices.json")), token.getType());
        List<PriceInfo> piceInfos = fuelData.stream()
                .filter(pi -> !pi.prices.isEmpty())
                .map(r -> new PriceInfo(r))
 //               .filter(pi -> !Double.isNaN(pi.amount))
                .toList();
    }
}

PriceInfo ist also eine Klasse, die die Daten enthält, die einen interessieren. id und amount waren das erst einmal so wie ich Dich verstanden habe.
Der Konstruktor könnte statt einem Konstruktor auch ein eigene Klasse sein - wäre halt dann eine typische Adapterklasse. Habe ich hier einfach einmal einfach gehalten.

Das Einlesen habe ich einfach gleich in eine ArrayList gemacht. Ein Array wie bei Dir würde aber auch gehen und dann hätte man statt .stream halt ein Arrays.stream(...).

Die gelesenen Daten streame ich, ich filtere dann die Elemente aus, die keine Preisinformationen enthalten. (Das hatte ich beim herunter schreiben erst einmal nach dem map gemacht.)

Im Test habe ich mir das einfach einmal angesehen im Debugger. Da habe ich keine Asserts geschrieben. Ist halt nur eine minimale Demo und kein UnitTest von einer Unit, die ich einsetzen will.

Das wäre aber dann so eine Möglichkeit, wie man gelesene Daten aus sogenannten Data Transfer Objects, DTOs in seine eigenen Entities bekommen könnte um dann besser damit zu arbeiten.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
B Json Objekt sinnvoll plätten? XML & JSON 1
W com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of XML & JSON 6
L JSON auslesen und Labels in GUI verwenden XML & JSON 13
mananana Frage zu JSON XML & JSON 3
N JSON export String Unicode? XML & JSON 6
L Json reader XML & JSON 15
megusta JSON umschreiben (converter)? XML & JSON 4
P verschachteltes json verändern XML & JSON 3
Avalon JSON flatten und wieder in DTO konvertieren XML & JSON 21
M Objekt zu jsonArray in .json datei hinzufügen ? XML & JSON 3
Z json inkl. Array/Verschachtelung erstellen XML & JSON 2
J Object in JSON Datei einlesen und als neues Object erzeugen (in ein Object Array) XML & JSON 29
Trèfle Formatierung v. JSON File XML & JSON 7
M json page 2 auslesen XML & JSON 1
K JSON mit GSON nutzen XML & JSON 4
S Java REST Client + Json XML & JSON 8
W Search Value in Json XML & JSON 6
K JSON-Bibliothek XML & JSON 5
M Großes Json Objekt benutzen XML & JSON 5
M Json auslesen XML & JSON 7
M Xml oder Json? XML & JSON 15
J JSON zu Java mit der GSON Google API XML & JSON 0
G Jackson JSON: Dynamische Serialisierung XML & JSON 6
W Json von URL Lesen (mit Gson Library) XML & JSON 3
W Json von URL Lesen XML & JSON 2
L Jackson JSON: Probleme beim einlesen XML & JSON 1
J JSon-Converter gesucht XML & JSON 2
Q Konvertierung von json zum Java Objekt nach vorgegebenem Schema XML & JSON 3
J JSon <-> XML zwecks Validierung XML & JSON 4
M [JSON] Wie Splitten? XML & JSON 14
G Mit JSON Java und C# verbinden XML & JSON 4
B DOMParser - Element filtern XML & JSON 1
flashfactor Filtern mittels XPATH XML & JSON 4
R Handler-Wechsel, SAX Parser bricht nach 8192 Byte ab XML & JSON 5
I Newlines nach childs erste ebene (dom) XML & JSON 3
K Docbook tranformieren nach LaTeX XML & JSON 2
sylo Nach Export wird SAXParseException nicht mehr geworfen XML & JSON 4
T XPath Problem: finden einer Node nach Attributswert XML & JSON 2
N xml nach Value durchsuchen XML & JSON 8
W String nach XML nach String verwandeln XML & JSON 4
D XML nach BME Cat Norm prüfen? XML & JSON 4
I Editor, der nur Elemente einfuegt, die nach xsd zulaessig XML & JSON 2
S leading whitespaces nach einem XMLOutputter XML & JSON 9
A Point2D.double nach XML XML & JSON 2
A html-File nach txt-File konvertieren XML & JSON 15
T Newbie Frage. CSS Stylesheet einlesen und suchen nach Tags XML & JSON 6
A Auf der Suche nach Bibliotheken oder wie parsen? XML & JSON 15
M RSS nach WML XML & JSON 9
V Datenverlust nach sortieren (nur beim serialisieren) XML & JSON 4
H Nach einem Attribut suchen und dann löschen XML & JSON 3
M jaxb binding nach set XML & JSON 9

Ähnliche Java Themen

Neue Themen


Oben