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

Android开发:如何从给定GsmCellLocation代码中获取目标格式字符串?

一、生成指定格式的GSMINFO字符串

要得到格式为type = gsm, lac = ..., cid = ..., psc = ...的字符串,最直接的方式是跳过JSON构建,直接通过字符串格式化拼接数据:

public static String getGSMInfo(GsmCellLocation location) {
    if (location == null) {
        return ""; // 可根据需求替换为默认提示内容
    }
    return String.format("type = gsm, lac = %d, cid = %d, psc = %d",
            location.getLac(),
            location.getCid(),
            location.getPsc());
}

如果必须基于你提供的现有方法逻辑(比如需要复用原有参数校验),也可以先获取JSON字符串再解析拼接:

// 调用原有方法获取JSON
String jsonResult = gsmCellLocationJSON(location);
if ("error".equals(jsonResult) || jsonResult.equals("{}")) {
    return "";
}
try {
    JSONObject json = new JSONObject(jsonResult);
    return String.format("type = gsm, lac = %d, cid = %d, psc = %d",
            json.getInt("lac"),
            json.getInt("cid"),
            json.getInt("psc"));
} catch (JSONException e) {
    return "error";
}
二、原方法return语句的执行逻辑

原方法包含两处return,执行规则如下:

  • catch块中的return "error";:当try块内的json.put()操作抛出JSONException(如键名不合法、值类型不匹配)时,会立即进入catch块执行这条return,方法直接终止,返回"error",不会继续执行后续代码。
  • 方法末尾的return json.toString();:两种场景会走到这里:
    1. 传入的location为null,跳过if代码块,直接执行该return,返回空JSON字符串{};
    2. location不为null,且try块内所有操作正常完成(无异常抛出),构建好JSON对象后执行该return,返回完整的JSON字符串。

注意:只要任意一条return语句被执行,方法会立刻结束,后续代码不会再运行。例如catch块的return触发后,不会走到方法末尾的return。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:33:34