1

I am trying to parse coordinates from a json string into the Location class in my program. I have already read the json file into the string variable coords. The problem is the string contains multiple coordinates but I only need the importantPlace lat and lng and none of the other coordinates or information but I don't know how to only use those parts of the json string to make a new Location object .

The Location class:

public class Location {

    public double lat;
    public double lng;

    public Location(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }
}

This is what coords contains:

{
  "country": "US",
  "square": {
    "northeast": {
      "lng": 5.18232,
      "lat": 42.91431
    }
    "southwest": {
      "lng": 5.18240,
      "lat": 42.91422
    },
  },
  "importantPlace": "Building",
  "coordinates": {
    "lng": 5.18234,
    "lat": 42.91427
  },
  "words": "trades.rare.cable",
  "map": "https://w3w.co/trades.rare.cable"
}

I know that to to parse everything I could use:

public Location parseCoords(String coords) {
    Location pos = new Gson().fromJson(coords, Location.class);
    return pos; 

But this won't work because the json string has multiple coordinates and parameters that Location class doesn't have.

Is there a way to only use the importantPlace lat and lng coordinates to make a new Location object?

RishtarCode47
  • 365
  • 1
  • 4
  • 18
  • 1
    You need to deserialise payload to `com.google.gson.JsonObject`, find required field and convert it to a class: `JsonObject root = gson.fromJson(jsoPayload, JsonObject.class);` `Location coordinates = gson.fromJson(root.get("coordinates"), Location.class);` – Michał Ziober Oct 26 '20 at 12:41

1 Answers1

0

I think you should make a full model to parse the entire String into java classes. You can also try to trim the string so only the "important" part will be left and then you can parse it using fromGson() method.