You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Swift中利用Google Places API从JSON数据创建Location对象

嘿,看起来你已经搞定了Google Places API数据获取的部分,接下来要把返回的JSON映射到你的Location对象对吧?这一步核心就是属性的对应转换,我给你分享几种主流语言的实现思路和代码示例,你可以按需取用~

核心思路:JSON字段到Location对象的映射

首先得明确Google Places API返回的JSON结构(对应你提到的字段)大概是这样的:

{
  "geometry": {
    "location": {
      "lat": 37.7749,
      "lng": -122.4194
    }
  },
  "rating": 4.5,
  "price_level": 2,
  "opening_hours": {
    "open_now": true
  },
  "photos": [
    {
      "photo_reference": "abc123",
      "height": 400,
      "width": 600
    }
  ]
}

你的Location对象需要把这些嵌套或下划线命名的字段,转换成符合你代码规范的属性(比如驼峰命名),同时要处理字段缺失的情况(比如部分餐厅没有评分或照片)。


JavaScript/TypeScript 实现

先定义你的Location类,再写转换函数:

// 定义Location类,用可选属性处理可能缺失的字段
class Location {
  lat: number;
  lng: number;
  rating?: number;
  priceLevel?: number;
  isOpenNow?: boolean;
  photoReferences: string[];

  constructor(
    lat: number,
    lng: number,
    rating?: number,
    priceLevel?: number,
    isOpenNow?: boolean,
    photoReferences: string[] = []
  ) {
    this.lat = lat;
    this.lng = lng;
    this.rating = rating;
    this.priceLevel = priceLevel;
    this.isOpenNow = isOpenNow;
    this.photoReferences = photoReferences;
  }
}

// JSON转Location的核心函数
function convertPlacesJsonToLocation(placesData: any): Location {
  // 提取坐标,用可选链+空值合并处理缺失字段
  const lat = placesData.geometry?.location?.lat ?? 0;
  const lng = placesData.geometry?.location?.lng ?? 0;

  // 映射其他字段,注意API的下划线命名转驼峰
  const rating = placesData.rating;
  const priceLevel = placesData.price_level;
  const isOpenNow = placesData.opening_hours?.open_now;

  // 提取照片引用
  const photoReferences = placesData.photos?.map((photo: any) => photo.photo_reference) ?? [];

  return new Location(lat, lng, rating, priceLevel, isOpenNow, photoReferences);
}

Java 实现(用Jackson库)

Java里常用Jackson处理JSON,先定义Location实体类,再写转换逻辑:

import java.util.List;

// Location实体类,用包装类处理空值
public class Location {
    private double lat;
    private double lng;
    private Double rating;
    private Integer priceLevel;
    private Boolean isOpenNow;
    private List<String> photoReferences;

    // 构造函数、Getter、Setter
    public Location(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }

    // 省略Getter和Setter,也可以用Lombok简化代码
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;

public class PlacesConverter {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Location convertJsonToLocation(String placesJson) throws Exception {
        JsonNode rootNode = objectMapper.readTree(placesJson);

        // 提取坐标
        double lat = rootNode.path("geometry").path("location").path("lat").asDouble();
        double lng = rootNode.path("geometry").path("location").path("lng").asDouble();
        Location location = new Location(lat, lng);

        // 处理评分
        if (rootNode.has("rating")) {
            location.setRating(rootNode.path("rating").asDouble());
        }

        // 处理价格等级
        if (rootNode.has("price_level")) {
            location.setPriceLevel(rootNode.path("price_level").asInt());
        }

        // 处理营业状态
        JsonNode openingHours = rootNode.path("opening_hours");
        if (!openingHours.isMissingNode()) {
            location.setIsOpenNow(openingHours.path("open_now").asBoolean());
        }

        // 处理照片引用
        JsonNode photos = rootNode.path("photos");
        List<String> photoRefs = new ArrayList<>();
        if (!photos.isMissingNode() && photos.isArray()) {
            for (JsonNode photo : photos) {
                photoRefs.add(photo.path("photo_reference").asText());
            }
        }
        location.setPhotoReferences(photoRefs);

        return location;
    }
}

Python 实现(用Dataclass)

Python用dataclass可以简化实体类定义,搭配内置json模块处理转换:

from dataclasses import dataclass
from typing import List, Optional
import json

@dataclass
class Location:
    lat: float
    lng: float
    rating: Optional[float] = None
    price_level: Optional[int] = None
    is_open_now: Optional[bool] = None
    photo_references: List[str] = None

    # 初始化空列表避免None
    def __post_init__(self):
        if self.photo_references is None:
            self.photo_references = []

# JSON转Location函数
def convert_places_json_to_location(places_dict: dict) -> Location:
    # 提取坐标,用get方法处理缺失字段
    geometry = places_dict.get("geometry", {})
    location = geometry.get("location", {})
    lat = location.get("lat", 0.0)
    lng = location.get("lng", 0.0)

    # 映射其他字段
    rating = places_dict.get("rating")
    price_level = places_dict.get("price_level")
    opening_hours = places_dict.get("opening_hours", {})
    is_open_now = opening_hours.get("open_now")

    # 提取照片引用
    photos = places_dict.get("photos", [])
    photo_references = [p.get("photo_reference") for p in photos if p.get("photo_reference")]

    return Location(
        lat=lat, lng=lng, rating=rating,
        price_level=price_level, is_open_now=is_open_now,
        photo_references=photo_references
    )

# 使用示例
places_json_str = '''{"geometry": {"location": {"lat": 37.7749, "lng": -122.4194}}, "rating":4.5, "price_level":2, "opening_hours":{"open_now":true}, "photos":[{"photo_reference":"abc123"}]}'''
places_dict = json.loads(places_json_str)
my_location = convert_places_json_to_location(places_dict)
print(my_location)

关键注意事项
  • 字段名对应:API返回的是下划线命名(比如price_level),你的Location如果用驼峰命名(比如priceLevel),一定要做好映射,别搞混。
  • 空值处理:部分餐厅可能没有评分、照片或营业状态数据,必须做空值判断,避免空指针/索引错误。
  • 照片使用:API返回的photo_reference是图片的引用,你需要用这个拼接成Google的图片URL才能直接显示(记得带上你的API Key)。

内容的提问来源于stack exchange,提问作者David Chopin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:12:37