I listen to the socket and it comes Json, but I can’t parse it to get a message
[private-meeting-chat.98,
{"success":true,"data":
{"message":"Fuhvvhjv",
"chat_message_type_id":1},
"socket":null}]
here is the code i use
privateChannel.listen("MeetingChatMessage", args -> {
Log.i("Log", Arrays.toString(args));
runOnUiThread(() -> {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(args);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject jsonDATA= jsonObject.getJSONObject("data");
String message = jsonDATA.getString("message");
Log.i("Log", message);
} catch (JSONException e) {
e.printStackTrace();
}
});
}
args comes to me, I can see it in the logs, but I can’t get information from it
From your comments, it seems that args is a list/array where the 2nd element is the response from the channel. So you need to access that element and convert to json.
JSONObject jsonObject = new JSONObject(args[1]);
JSONObject jsonDATA= jsonObject.getJSONObject("data");
String message = jsonDATA.getString("message");
Also, since it's not working, did you check what the error stacktrace is?
Related
I am trying to produce and send via JAVA a JSON file and when I am trying to add a nested object with an array in order to fit an application's protocol (which is not important to the question) the java program cannot send the file because of an HTTP error, code 415 (unsupported media type), which is strange because the produced JSON works when I copy it in the destined application (Google's DialogFlow). In other words, JSON is functional but JAVA (version 1.8) does not recognize it. Does anyone have any ideas why that happens?
When the part with the JSONArray in not included in the JSON file the request is sent without problem (see code below). I have tried changing the content-type from "application/json;charset=utf8" to "application/json;charset=utf-8" or "application/json" but nothing worked (this part in not included in the code because the changes that resulted in JSON not working were in the block below).
Part not working:
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
payload.put("title", "Thanks");
payload.put("message", "Thank you");
arrayJson.put(payload);
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
meta.put("payload", arrayJson);
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}
The part working (without the extra layer in JSON, e.g. the payload JSON object and the arrayJson JSON array):
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}
Ok, I found the problem. I should have transformed the arrayJson from JSONArray type to string.
In other words, instead of
meta.put("payload", arrayJson);
I should have
meta.put("payload", arrayJson.toString());
or make the arrayJson in a string format from the beginning.
In my Android application, I need to send an array as body (payload information) to a POST url.
In body, there are two params:
1. "env" : "dev"
2. "dNumber" : tn("+1232323"); // here I need to send an array.
Edited question: I need to send phone as an array like ["123131","4545545"]
I pass the array as created a JSON array and convert to string and passed.
private String tn(String tn) {
String json = "";
try {
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, tn);
json = jsonArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
and full code is:
try {
URL url;
HttpURLConnection urlConnection;
url = new URL(makeCallUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", String.format("%s %s", "Basic", secretKey));
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
// Setup the body of the url
JSONObject json = new JSONObject();
json.put("env", "dev");
json.put("destNumbers", tn("+123123"));
// Write the body on the wire
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
writer.write(json.toString());
writer.flush();
writer.close();
} catch (IOException e) {
Log.d(TAG, "IOException:" + e.getMessage());
e.printStackTrace();
}
If I try this, I got 400, Bad request exception.
Please help me to pass an array to POST api
I solved my problem using JSONArray and pass the array.
// creating json array
JSONArray numberArray = new JSONArray();
numberArray.put(0, tn);
// send the array with payload
JSONObject json = new JSONObject();
json.put("env", "DEV");
json.put("destNumbers", numberArray);
Now I get array as following:
destNumbers = ["3434343","3434334]
Update your tn() method. Instead of returning String it should return JSONArray.
private JSONArray tn(String tn) {
JSONArray jsonArray = new JSONArray();
try {
jsonArray.put(0, tn);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray ;
}
Although if still the 400 Bad request error occur than confirm and verify the request payload with your json.
I'm a complete beginner, especially when is comes to JSON parsing.
I've been using the google directions API
to make a basic navigation app that draws a route from two locations, which is all great. However after trying for hours to parse the "steps" from the API, I still can't make it work.
I've used this example https://github.com/hiepxuan2008/GoogleMapDirectionSimple
to parse the JSON to draw the route.
This is done in the following code. (full code on github "Directionfinder.java")
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
Heres how the JSON typically looks. http://pastebin.com/czYkBWWU
I need to parse "maneuver", "start_location", "distance", "start_location and the position from every step of a given route.
It seems fairly easy to parse this, but I just can't figure out how.
Any help will be greatly appreciated!
Here is full code. I Run it in my Device and get Successfull result. If you face problem then let me know.
try {
List<Route> routes=new ArrayList<Route>();
JSONObject mainJSON=new JSONObject(jsonJ);
JSONArray jarray1=mainJSON.getJSONArray("routes");
JSONObject jobj1=jarray1.getJSONObject(0);
JSONArray jarray2=jobj1.getJSONArray("legs");
JSONObject jobj2=jarray2.getJSONObject(0);
JSONArray stepArray=jobj2.getJSONArray("steps");
for (int i=0;i<stepArray.length();i++){
Route route=new Route();
JSONObject jobj5=stepArray.getJSONObject(i);
JSONObject disOBJ=jobj5.getJSONObject("distance");
JSONObject durOBJ=jobj5.getJSONObject("duration");
JSONObject endOBJ=jobj5.getJSONObject("end_location");
JSONObject polOBJ=jobj5.getJSONObject("polyline");
JSONObject startOBJ=jobj5.getJSONObject("start_location");
route.startAddress=jobj2.getString("start_address");
route.endAddress=jobj2.getString("end_address");
if (jobj5.has("maneuver")){
route.maneuver=new Maneuver(jobj5.getString("maneuver"));
}
route.distance=new Distance(disOBJ.getString("text"),disOBJ.getString("value"));
route.duration=new Duration(durOBJ.getString("text"),durOBJ.getString("value"));
route.startLocation=new LatLng(startOBJ.getDouble("lat"),startOBJ.getDouble("lng"));
route.endLocation=new LatLng(endOBJ.getDouble("lat"),endOBJ.getDouble("lng"));
route.points=decodePoluLine(polOBJ.getString("points"));
routes.add(route);
}
} catch (JSONException e) {
e.printStackTrace();
}
I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples
My PHP file:
<?php
include("ConnectDatabase.php");
$Username = mysql_real_escape_string($_POST['Username']);
$Password = mysql_real_escape_string($_POST['Password']);
$q = mysql_query("SELECT Username, Password FROM Users
where Username = '".$Username."' and
Password = '".$Password."'", $con);
if(mysql_num_rows($q) > 0){
$row = mysql_fetch_assoc($q);
print json_encode($row);
}else{
print "0";
}
?>
I tried to parse that by the following to get a value,but it got null values both userJson and passJson:
public void parseJson(String result){
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
userJson = jArray.getJSONObject(i).getString("Username").toString();
passJson = jArray.getJSONObject(i).getString("Password").toString();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Anyone can see my mistake ? Thank you
PS This is my older post that related to this post.
I would think they end up null cuz the first line doesn't work. It's not a JSONArray as you have generated.
try {
JSONObject root = new JSONObject(result);
username = root.getString("Username");
password = root.getString("Password");
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
something like that.