如何将获得的这个 String 传递给 jsonObject 格式?

执行代码我得到一个具有以下值的字符串"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]

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


MYYA
浏览 70回答 1
1回答

人到中年有点甜

该字符串不是有效的 JSON,而是您想要的,可以使用如下简单的 Java 代码实现public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {&nbsp; &nbsp; String test = "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "batteryLevel=27&batteryCurrent=0&baterryVolts=3.63";&nbsp; &nbsp; String[] result = test.split("&");&nbsp; &nbsp; Map<String, String> map = new HashMap<String, String>();&nbsp; &nbsp; for (String string : result) {&nbsp; &nbsp; &nbsp; &nbsp; String[] str = string.split("=");&nbsp; &nbsp; &nbsp; &nbsp; map.put(str[0], str[1]);&nbsp; &nbsp; }&nbsp; &nbsp; double pressure = Double.valueOf(map.get("pressure"));&nbsp; &nbsp; double no2C = Double.valueOf(map.get("no2C"));&nbsp; &nbsp; double tempreture = Double.valueOf(map.get("temperature"));&nbsp; &nbsp; double o3C = Double.valueOf(map.get("o3C"));&nbsp; &nbsp; double cOC = Double.valueOf(map.get("coC"));&nbsp; &nbsp; 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 值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java