【问题标题】:How can I pass this String obtained to jsonObject format?如何将获得的这个字符串传递给 jsonObject 格式?
【发布时间】:2019-05-29 10:39:32
【问题描述】:

执行代码我得到一个字符串,其值为"idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&batteryLevel=27&batteryCurrent=0&baterryVolts=3.63"

我的目标是把那个String转换成JsonObject格式,每个值都是分开的,即idstation = 6107AAE80593E4B2等,以后可以继续处理数据

我们的想法是以 no2 的值为例,并将其保存在类型为 (Map String, Object) 的变量中

eventPayload.put ("no2", String.valueOf (no2));

字符串的值被编码在变量“sinCifrar”中

我尝试了以下代码,但我遇到了问题:

'String jsonString = sinCifrar;
JSONObject jsonk = new JSONObject(jsonString);
            no2 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("no2C")/1000)*46.0055)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            co = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("coC")/1000)*28.01)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            o3 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("o3C")/1000)*48.0)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;'

我收到以下错误:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

由于它不是一开始就创建的字符串,而是执行了几个方法后得到的,所以我不能把它保留为要求的格式,知道吗?

【问题讨论】:

标签: java json mule-esb


【解决方案1】:

字符串不是一个有效的 JSON,但是你想要的,可以使用下面的简单 java 代码来实现

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    String test = "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380"
            + "&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&"
            + "batteryLevel=27&batteryCurrent=0&baterryVolts=3.63";
    String[] result = test.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String string : result) {
        String[] str = string.split("=");
        map.put(str[0], str[1]);
    }
    double pressure = Double.valueOf(map.get("pressure"));
    double no2C = Double.valueOf(map.get("no2C"));
    double tempreture = Double.valueOf(map.get("temperature"));
    double o3C = Double.valueOf(map.get("o3C"));
    double cOC = Double.valueOf(map.get("coC"));
    System.out.println("Pressure:: "+pressure+" , no2c :: "+no2C+", tempreture:: "+tempreture+" ,o3C:: "+o3C+" ,coC:: "+cOC);
}

输出

Pressure:: 93926.656 , no2c :: 0.0, tempreture:: 22.38 ,o3C:: 8.2103271 ,coC:: 0.44092381

从地图中你可以得到任何你想要的Key值。

【讨论】:

  • 谢谢,我已将您的地图 替换为 Map map = new LinkedHashMap ();这样我就可以创建一个 jsonObject: JSONObject jsonk = new JSONObject (map);并从那里保存在另一个 Map eventMap = new LinkedHashMap () 中收集的值;处理完价值观之后。这样代码最终可以正常工作,至少它给了我感觉,明天我将进行测试,从 waspmote 传感器发送新数据,我确认你
猜你喜欢
  • 1970-01-01
  • 2011-09-30
  • 2019-07-13
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多