如何在C#中转换Google Places Autocomplete API返回的JSON格式
在C#中转换Google Places Autocomplete API的JSON格式
核心实现方案
我们可以用两种主流方式完成JSON结构转换:一是用生态最常用的第三方库Newtonsoft.Json,二是使用.NET Core 3.0+内置的System.Text.Json,以下是具体步骤:
方案1:使用Newtonsoft.Json(推荐新手)
1. 安装依赖
在NuGet包管理器中搜索并安装Newtonsoft.Json,或者在Package Manager Console执行命令:
Install-Package Newtonsoft.Json
2. 定义输入输出实体类
通过JsonProperty特性映射JSON字段与类属性,解决字段名不一致的问题:
// 对应Google API返回的原始结构 public class GooglePlacePrediction { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("place_id")] public string PlaceId { get; set; } } public class GooglePlacesResponse { [JsonProperty("predictions")] public List<GooglePlacePrediction> Predictions { get; set; } [JsonProperty("status")] public string Status { get; set; } } // 对应你需要的目标输出结构 public class TransformedPlaceItem { [JsonProperty("description")] public string Description { get; set; } [JsonProperty("id")] public string Id { get; set; } } public class TransformedResponse { [JsonProperty("success")] public bool Success { get; set; } [JsonProperty("message")] public string Message { get; set; } [JsonProperty("data")] public List<TransformedPlaceItem> Data { get; set; } }
3. 编写转换逻辑
先反序列化原始JSON到输入模型,再映射为目标模型,最后序列化回JSON:
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; // 替换为你从API获取到的JSON字符串 string googleRawJson = @"{""predictions"": [{""description"": ""Frankfurt am Main, Deutschland"",""place_id"": ""ChIJxZZwR28JvUcRAMawKVBDIgQ""},{""description"": ""Frankfurt (Oder), Deutschland"",""place_id"": ""ChIJb_u1AiqYB0cRwDteW0YgIQQ""},{""description"": ""Frankfurt Hahn Flughafen (HHN), Lautzenhausen, Deutschland"",""place_id"": ""ChIJX3W0JgQYvkcRWBxGlm6csj0""}],""status"": ""OK""}"; // 反序列化原始JSON var googleResponse = JsonConvert.DeserializeObject<GooglePlacesResponse>(googleRawJson); // 判断请求成功状态:Google API返回"OK"视为成功 bool isSuccess = googleResponse.Status == "OK"; // 映射为目标结构 var transformedResult = new TransformedResponse { Success = isSuccess, Message = googleResponse.Status, Data = googleResponse.Predictions.Select(pred => new TransformedPlaceItem { Description = pred.Description, Id = pred.PlaceId }).ToList() }; // 序列化为带缩进的目标JSON string targetJson = JsonConvert.SerializeObject(transformedResult, Formatting.Indented);
方案2:使用.NET内置System.Text.Json
如果不想依赖第三方库,.NET Core 3.0+自带的System.Text.Json也能实现:
1. 定义实体类
用JsonPropertyName特性替代JsonProperty:
using System.Text.Json.Serialization; public class GooglePlacePrediction { [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("place_id")] public string PlaceId { get; set; } } // 其他输入输出模型同理,替换JsonProperty为JsonPropertyName
2. 转换代码
using System.Text.Json; using System.Linq; // 反序列化原始JSON var googleResponse = JsonSerializer.Deserialize<GooglePlacesResponse>(googleRawJson); // 映射目标结构 var transformedResult = new TransformedResponse { Success = googleResponse.Status == "OK", Message = googleResponse.Status, Data = googleResponse.Predictions.Select(pred => new TransformedPlaceItem { Description = pred.Description, Id = pred.PlaceId }).ToList() }; // 序列化带缩进的JSON var serializeOptions = new JsonSerializerOptions { WriteIndented = true }; string targetJson = JsonSerializer.Serialize(transformedResult, serializeOptions);
关键细节说明
- Success字段判断:可根据Google API的状态码规则调整,比如
"ZERO_RESULTS"是否算成功,完全根据你的业务需求定义。 - 格式化输出:两种方案都支持生成带缩进的JSON,方便调试和阅读。
内容的提问来源于stack exchange,提问作者h4yv3n
相关产品推荐
相关产品推荐

