How can I pass this String obtained to jsonObject format? - java

Executing the code I get a String with the following value "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"
My goal is to convert that String into JsonObject format where each value is separated, that is, idstation = 6107AAE80593E4B2, etc., and to be able to continue treating the data later
the idea is to take for example the value of no2 and save it in a variable of type (Map String, Object)
eventPayload.put ("no2", String.valueOf (no2));
the value of the string is coded in the variable "sinCifrar"
I tried the following code, but I have problems:
'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;'
I get the following error:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
Since it is not a string created from the beginning, but it is obtained after executing several methods, I can not leave it with the requested format, any idea?

The string is not a valid JSON but what you want , can be acheived using simple java code as below
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);
}
output
Pressure:: 93926.656 , no2c :: 0.0, tempreture:: 22.38 ,o3C:: 8.2103271 ,coC:: 0.44092381
From the map you can get any Key value you want.

Related

Why my var return incompatibility problem with error 13?

I'm trying to parse Json in VBA.
I'm collecting data from an API that returns a json format in a string.
I use JsonConverter to parse my string.
Now when i want to search on it, i got an error 13 incompatibility type.
See my Java API below :
#GetMapping("/rest/collectData/excel/exportAll")
public HashMap<Object, Object> collectAll(){
HashMap<Object, Object> result = new HashMap<>();
String sql = "SELECT affair_code AS codeAffair, name, amount, end_date AS state FROM service_record WHERE affair_code IS NOT NULL AND affair_code != ''";
List<Map<String, Object>> allServiceRecords = jdbcTemplate.queryForList(sql);
if(allServiceRecords != null && allServiceRecords.size() >0){
result.put("result", true);
for(Map<String, Object> serviceRecord : allServiceRecords){
HashMap<Object, Object> details = new HashMap<>();
if(result.containsKey(serviceRecord.get("codeAffair"))){
details.put("alone", false);
details.put("message", "Plusieurs prestations ont été trouvées.");
} else {
details.put("alone", true);
details.put("name", (String) serviceRecord.get("name"));
details.put("amount", (Double) serviceRecord.get("amount"));
details.put("state", ((Date) serviceRecord.get("state")).compareTo(new Date()) < 0 ? "En cours" : "Clos");
}
result.put(serviceRecord.get("codeAffair"), details);
}
} else{
result.put("result", false);
result.put("error", "La liste n'est pas définie, ou vide.");
}
return result;
}
It returns json :
{"03-045251":{"alone":true,"amount":0.0,"name":"name1","state":"En cours"},"03_05494":{"alone":true,"amount":16743.0,"name":"name2","state":"En cours"}}
First, i execute sql request to collect my data and put it in a map.
Then, i send this map to my excel VBA.
Now see my VBA :
Sub JsonDataSqwal()
firstRow = Range("A" & 11).End(xlDown).Row
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Dim httpObject As Object
Set httpObject = CreateObject("MSXML2.XMLHTTP")
sUrl = "http://localhost/rest/collectData/excel/exportAll"
sRequest = sUrl
httpObject.Open "GET", sRequest, False
httpObject.send
sGetResult = httpObject.responseText
If Not IsNull(sGetResult) Then
Dim oJson As Object
JsonConverter.JsonOptions.AllowUnquotedKeys = True
Set oJson = JsonConverter.ParseJson(sGetResult)
Dim i As Long
For i = firstRow To lastRow
Dim codeAffString As String
codeAffString = Cells(i, 4)
Debug.Print oJson(codeAffString)("name")
Next i
End If
End Sub
For the moment, i try to print my data. the loop collects values from a column, which contains all my codeAffair as 00_00000 or 00-00000
It is this data that i try to use in my vba code with the var codeAffString.
When i execute my code, i'm always getting error 13 about type incompatibility.
To solve this, i tried many things :
to add quote to my var
To rename my HashMap as HashMap<String, Object>
To allow unquoting keys
To change my back office program
To replace my value like """" + codeAffairString + """"
To replace my var with a fix String "00_00000". It works in this case.
To check the type of my var with VarTyp function which returns 8 for String index.
Now i Have no other idea to solve my problem..
If someone see where is my mistake..
Thank you !
Just a quick test:
I used the JSON string you gave and the value you gave for codeAffString to build a minimal reproducible example and it does not produce any errors:
Sub test()
Const JsonString As String = "{""03-045251"":{""alone"":true,""amount"":0.0,""name"":""name1"",""state"":""En cours""},""03_05494"":{""alone"":true,""amount"":16743.0,""name"":""name2"",""state"":""En cours""}}"
Const codeAffString As String = "03-045251"
Dim oJson As Object
JsonConverter.JsonOptions.AllowUnquotedKeys = True
Set oJson = JsonConverter.ParseJson(JsonString)
Debug.Print oJson(codeAffString)("name") ' outputs name1
End Sub
The error you describe occurs if codeAffString cannot be found in the JSON.
Test it by the following in your code:
For i = firstRow To lastRow
Dim codeAffString As String
codeAffString = Cells(i, 4)
If IsEmpty(oJson(codeAffString)) Then
Debug.Print codeAffString & " does not exist in the json"
Else
Debug.Print oJson(codeAffString)("name")
End If
Next i

Obtain specific part of a string with JSON Format java

I have a question on how would be the best way to get the information from a string but that has JSON format.
{
"internal_id":"1234",
"moreInformation":"Failed authentication for user."
}
In this case, I want to get the value of "internal_id" and I already did, with subtring, lastIndexOf and indexOf
public static String returnInternalCode(String json){
String internalCode = json.substring(json.lastIndexOf("\"internal_id\":\"") + "\"internal_id\":\"".length(), json.length() - 1);
if (json.lastIndexOf("\"internal_id\":\"") == -1) return null;
return internalCode.substring(0, internalCode.indexOf("\""));
}
I also tried several JSONs with order changes that don't have the data and it also worked. I leave the full class of tests I did:
public class Test {
public static void main(String[] args) {
// Original JSON
String json = "{\"internal_id\":\"999999\",\"moreInformation\":\"Failed authentication for user, 1 authentication attempt remaining.\"}";
// Other JSON order
String json2 = "{\"moreInformation\":\"Failed authentication for user. Invalid response.\", \"moreInformation2\":\"Failed authentication for user. \", \"internal_id\":\"45678\"}";
// JSON without the internal_id
String json3 = "{\"moreInformation\":\"Failed authentication for user. Invalid response.\"}";
// JSON without moreInformation
String json4 = "{\"internal_id\":\"999999\"}";
System.out.println("JSON: ".concat(json4));
System.out.println("internalId: " + returnInternalId(json4));
System.out.println("moreInformation: " + returnMoreInformation(json4));
}
public static String returnInternalId(String json){
String internalCode = json.substring(json.lastIndexOf("\"internal_id\":\"") + "\"internal_id\":\"".length(), json.length());
if (json.lastIndexOf("\"internal_id\":\"") == -1) return null;
return internalCode.substring(0, internalCode.indexOf("\""));
}
public static String returnMoreInformation(String json){
String moreInformation = (json.substring(json.lastIndexOf("\"moreInformation\":\"") + "\"moreInformation\":\"".length(), json.length()));
if (json.lastIndexOf("\"moreInformation\":\"") == -1) return null;
return moreInformation.substring(0, moreInformation.indexOf("\""));
}
}
I would like to know if there are better ways to do what I did, such as with StringBuilder or StringBuffer and also to find out which way uses less memory or is faster to run, how do I know that? How long does it take to execute a method?
Thank you very much!
You can extract the values this way; Using Simple-json library
JSONObject jobj = (JSONObject) parser.parse(yourJsonString); // Pass the Json formatted String
String internal_id = (String) jobj.get("internal_id"); // Extract the value from your key
System.out.println(internal_id); // 1234

how to Parse Map value Data in android

Map<String, String> map =dataSnapshot.getValue(Map.class);
String MR_ID = map.get("MR_ID");
String JOB_TITLE = map.get("JOB_TITLE");
String JOB_TYPE = map.get("JOB_TYPE");
String Delv_ADDR=map.get("Delv_ADDR");
DataSnapshot { key = platformdb, value =
{MR_RELATIONS={CUSTOMERS={ORDERS={INVENTORY=, Delv_ADDR=D-103
LaxmiNagar New Delhi, ORDER_ID=}}}, MR_SCHEDULE={MR_ID=, JOB_TITLE=,
GEO_LINK=, JOB_TYPE={TSP={TSP_ADDR=, TSP_ID=, GEO_LINK=, TSP_NAME=},
SCC={SCC_ID=, SCC_ADDR=, GEO_LINK=, SCC_NAME=}, CUSTOMER={GEO_LINK=,
CUST_NAME=, CUST_ID=, CUST_ADDR=}}, JOB_ID=, TRANS_SRC=, TRANS_DEST=},
MR_POOL={FREE_MR=, BUSY_MR={77889992222={IS_BUSY=false,
GEO_LINK=8yyttrd}}}} }
This is my Data i am getting in map i want to Parse and and get value of Delv_ADDR But i am unable to get i am getting Null value please suggest me how to get data of that
From the attached input it seems that there is only one entry in the map with key platformdb and value as MR_RELATIONS=....
If you are doing String MR_ID = map.get("MR_ID"); then it will probably return you null as there is no entry in the map with key MR_ID.
What you should be doing instead is retrieve the value against the key by doing the following:
String response = map.get("platformdb");
And then parse this response String to extract the desired values.
Since, response does not seems to be JSON you can try using native String functions.
For example, to extract MR_ID from response you can do the following:
String response = map.get("platformdb");
String MR_ID = response.substring(response.indexOf("MR_ID=") + 6,
response.indexOf("MR_ID=") + response.indexOf(","));
String Delv_ADDR = response.substring(response.indexOf("Delv_ADDR=") + 10,
response.indexOf("Delv_ADDR=") + response.indexOf(","));

Convert JSON object with duplicate keys to JSON array

I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code
As of today the org.json library version 20170516 provides accumulate() method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);
Output:
{
"a":"b",
"c":["d","e"],
"f":"g"
}
I want to remove the repeated keys by combining their values into an array.
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into Map<String, List<String>> without using any library.
Sample code:
String jsonString = ...
// remove enclosing braces and double quotes
jsonString = jsonString.substring(2, jsonString.length() - 2);
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = keyValue[1];
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
output:
{
"f": ["g"],
"c": ["d","e"],
"a": ["b"]
}
In order to accomplish what you want, you need to create some sort of custom class since JSON cannot technically have 2 values at one key. Below is an example:
public class SomeClass {
Map<String, List<Object>> values = new HashMap<String, List<Object>>();
public void add(String key, Object o) {
List<Object> value = new ArrayList<Object>();
if (values.containsKey(key)) {
value = values.get(key);
}
value.add(o);
values.put(key, value);
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
JSONArray tempArray = null;
for (Entry<String, List<Object>> en : values.entrySet()) {
tempArray = new JSONArray();
for (Object o : en.getValue()) {
tempArray.add(o);
}
json.put(en.getKey(), tempArray);
}
return json;
}
}
You can then retrieve the values from the database, call the .add(String key, Object o) function with the column name from the database, and the value (as the Object param). Then call .toJson() when you are finished.
Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
public static String repeatedKeysToArrays(String jsonIn) throws JSONException
{
//This assumes that the json is flat
String jsonString = jsonIn.substring(2, jsonIn.length() - 2);
JSONObject obj = new JSONObject();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = "";
if (keyValue.length>1) value = keyValue[1];
if (!obj.has(key)) {
obj.put(key, value);
} else {
Object Oold = obj.get(key);
ArrayList<String> newlist = new ArrayList<String>();
//Try to cast as JSONArray. Otherwise, assume it is a String
if (Oold.getClass().equals(JSONArray.class)) {
JSONArray old = (JSONArray)Oold;
//Build replacement value
for (int i=0; i<old.length(); i++) {
newlist.add( old.getString(i) );
}
}
else if (Oold.getClass().equals(String.class)) newlist = new ArrayList<String>(Arrays.asList(new String[] {(String)Oold}));
newlist.add(value);
JSONArray newarr = new JSONArray( newlist );
obj.put(key,newarr);
}
}
return obj.toString();
}

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Categories