add JSONArray within a JSONObject - java

I'm making an application to send notifications using OneSignal and must do a POST request in JSON format.
To send notification to a user I have to use the include_player_ids argument which have to be an array because it is possible to send to multiple users the same notification (in my case I only send notification to one user).
I use a JSONArray to create this array but when adding it to the JSONObject, there are extra quotes for the field include_player_ids.
What I have:
{
"headings": {"en":"my_title"},
"contents": {"en":"my_text"},
"include_player_ids": "[\"my-player-id\"]",
"app_id":"my-app-id"
}
As you can see, there is some quote around the array [ ].
I guess it's what is making the response error from OneSignal :
errors":["include_player_ids must be an array"]
What I want :
...
"include_player_ids": ["my-player-id"]
...
It is weird because adding JSONObject to JSONObject doesn't do this even though it is quite similar as you can see with the headings / contents fields
My code :
import org.json.JSONException;
import org.json.JSONObject;
import org.json.alt.JSONArray;
JSONObject headings = new JSONObject();
JSONObject contents = new JSONObject();
JSONArray player_id = new JSONArray();
JSONObject notification = new JSONObject();
try {
notification.put("app_id", appId);
notification.put("include_player_ids", player_id);
player_id.put(idUser);
headings.put("en", "my_title");
contents.put("en", "my_text");
notification.put("headings", headings);
notification.put("contents", contents);
} catch (JSONException e) {
System.out.println("JSONException :" + e.getMessage());
}
idUser is a String
Thanks in advance for any help,

I believe the problem is that you're using org.json.alt.JSONArray instead of org.json.JSONArray. I'm not familiar with that class, but I suspect JSONObject.put is just calling toString() on it rather than treating it as an existing JSON array. Here's a short but complete example that doesn't have the problem:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray; // Note the import here
public class Test {
public static void main(String[] args) throws JSONException {
JSONArray playerIds = new JSONArray();
playerIds.put("a");
playerIds.put("b");
JSONObject notification = new JSONObject();
notification.put("include_player_ids", playerIds);
System.out.println(notification);
}
}
Output:
{"include_player_ids":["a","b"]}

Related

how to get same fields from jsonArray

using gson, I parsed data in json format and now I need to extract the value "dt_txt" and their value "temp" from this data and I don’t understand how to pull and paste them into the collection where the key is "dt_txt" and its value is "temp "
The data that I received: https://imgur.com/a/qAxwEri
package testClassPackage;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class weatherParse {
public static void main(String[] args) throws IOException {
String sURL = "http://api.openweathermap.org/data/2.5/forecast/?q=Odessa,ua&APPID=518a64dd48106aa542464d3bd94d12ce"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray message = rootobj.get("list").getAsJsonArray();
for (int i = 0; i < message.size(); i++) {
System.out.println();
}
System.out.println(message);
}
}
iterate over the JsonArray(message I changed to messages here) as JsonElement and get main object from the element then fetch th corresponding temp.
Map<String,String> data = new HashMap<>();
for(JsonElement lst : messages) {
JsonObject lstObject = lst.getAsJsonObject();
JsonObject el = (JsonObject) lstObject.get("main");
System.out.println(lstObject.get("dt_txt").getAsString() +" "+el.get("temp").getAsString());
data.put(lstObject.get("dt_txt").getAsString(), el.get("temp").getAsString());
}

parse json string using simple-json

I have read the posts that appeared to be the same as my question but I must be missing something. My environment is Eclipse Mars. My JAVA is 1.7 and I have imported json-simple. I simply wish to parse the json that is returned from my web service. I control the web service if I need to modify its output. I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array. I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]
Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class JsonParser
{
private static JSONObject _jsonInput;
public static void main(String[] args)
{
//TODO
try{
JSONParser parser = new JSONParser();
Object obj = JSONValue.parse(args[0]);
JSONArray array=(JSONArray)obj;
String name = array.get(3).toString();
System.out.println(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
}
The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
String name = array.get(3).toString();

Parsing JSON data in Java

I want to parse the some data from this page:
http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
The data I want to parse is the titles however I am unsure how I can extract the data. This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test
{
public Test() { }
public static void main(String[] args)
{
URL url;
HttpURLConnection connection = null;
InputStream is = null;
JSONParser parser = new JSONParser();
try
{
url = new URL("http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String reply;
while ((reply = theReader.readLine()) != null)
{
System.out.println(reply);
Object obj = parser.parse(reply);
JSONObject jsonObject = (JSONObject) obj;
String title = (String) jsonObject.get("time");
System.out.println(title);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This just returns null. Can anybody tell me what I need to change? Thanks.
If you read the javadoc of JSONObject#get(String) which is actually HashMap.get(String), it states
Returns: the value to which the specified key is mapped, or null if
this map contains no mapping for the key
Your JSON does not contain a mapping for the key time.
Edit:
If you meant title instead of time, take this extract of the JSON
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
You need to first get schedule as a JSONObject, then service as a JSONObject, and then title as a normal String value. Apply this differently depending on the type of JSON value.
use something like JSONGen to better understand your data structures, maybe even map your data to the generated objects using google-gson library

Why does my JSON-Simple JSONArray give me a nullpointer exception?

I'm following this tutuorial here, and my JSON object is near enough the same, except I have this sort of format:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is my relevant code:
Object obj = parser.parse(new FileReader("exampleJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
Then my program goes off an gets the values form the keys etc. Or it would but I get a NullPointerException from eclipse. Why is this?
It should unpackage my .json file into jsonObject, unpackage the "user" key as a JSONObject user, then unpackage the "SomeList" key as a JSONArray called list. Except when it does so it must be trying to put one of val1 or val2 into a part of the JSONArray that does not exist and just points into the abyss of null. What have I done to deserve this wrong ?
How do I fix my program?
Your code is working well for me
public class App {
public static void main(final String[] args) throws FileNotFoundException, IOException, ParseException {
final Object obj = new JSONParser().parse(new FileReader("D:/a.json"));
final JSONObject jsonObject = (JSONObject) obj;
final JSONObject user = (JSONObject) jsonObject.get("user");
final JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
File D:/exampleJson.json
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
output is
["val1","val2"]
Using the exact same json file:
{"user":{
"SomeKeys":"SomeValues",
"SomeList":["val1","val2"]
}
}
Here is the code I use (with the imports to really make sure we have the same ones):
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test {
public static void main(String[] args) throws Exception {
Object obj = new JSONParser().parse(new FileReader("t.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject user = (JSONObject) jsonObject.get("user");
JSONArray list = (JSONArray) user.get("SomeList");
System.out.println(list);
}
}
And here is the output:
["val1","val2"]
I used maven and m2e to import the library. The version used for this test was json-simple-1.1.jar.

Cannot retrieve data from MySQL table which matches specific "uid"

I am trying to learn more about MySQL and using Java (on Android) to access and retrieve information from a database on my WAMS server. The way my app is setup is that it has an initial login screen which also grabs the "uid" of the username that's logging in (from a different table) and stores it.
Upon login (which is functional - I setup a toast notification that displays the retrieved username and uid of the user logging in), it goes to a new screen (dashboard.xml) which has a TextView field setup to display the retrieved data (from table posted below) associated with the stored "uid". Here is the table I am trying to pull data from:
http://db.tt/4izVQuGB
Now, I have setup a PHP file that queries my db for rows that are associated with a specific "uid". I have tested this file using an HTML form.
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb)or die("database selection error");
//Retrieve the User ID
$uid = $_POST['uid'];
//Query
$query = mysql_query("SELECT * FROM node WHERE uid='$uid' AND type='goal'");
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
while($results=mysql_fetch_assoc($query)) {
//Store the returned data into a variable
$output = $results;
//encode the returned data in JSON format
echo json_encode($output);
}
mysql_close();
}
The result I get by testing the PHP file using uid value of 1 is:
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the
hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
Now, I have written some android code which sets up httppost and is supposed to retrieve the "titles" in my database table. I know it is wrong (obviously since it doesn't work) but I am confused as to what to do next.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Dashboard extends Activity implements OnClickListener {
// variable declarations
String uid = "1";
// create textview to display retrieved data
TextView display;
HttpClient httpclient;
HttpPost httppost;
HttpResponse httpresponse;
HttpEntity httpentity;
ArrayList<NameValuePair> resultArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
display = (TextView) findViewById(R.id.test);
// initialize HttpClient
httpclient = new DefaultHttpClient();
// initialize HttpPost
httppost = new HttpPost("http://192.168.1.112/android/fetch.php");
try {
// Create new List
List<NameValuePair> resultList = new ArrayList<NameValuePair>();
resultList.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(resultList));
httpresponse = httpclient.execute(httppost);
httpentity = httpresponse.getEntity();
InputStream instream = entity.getContent();
try {
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
JSONObject jData = null;
for (int i = 0; i < jArray.length(); i++) {
jData = jArray.getJSONObject(i);
String goals = jData.getString("title");
display.setText(goals);
}
//} catch (JSONException e) {
//Toast.makeText(this, "No entries found", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
Notifications error = new Notifications();
error.userPassErrorDialog();
}
}
private static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I get the following error when testing it in the Android emulator:
http://db.tt/2vg9MqYh
Any help or suggestions will be greatly appreciated.
In your Android app, you expect a JSONArray:
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
However, in your PHP file you only output multiple separate JSON objects instead of a real array. I think, you should collect all items from the database in an PHP array first and then encode and output it only once.
My PHP skills are a bit rusted, but I hope this one will work:
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
$output = array();
while($results = mysql_fetch_assoc($query)) {
// append row to output
$output[] = results
}
mysql_close(); // shouldn't that be outside the if block?
//encode the returned data in JSON format
echo json_encode($output);
}
I would expect the output then to be like this (maybe without indentation):
[
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
]
The problem lies in encoding and decoding of JSON. from your JSON response it looks like you are receiving JSON object from server also please try to validate you JSON response here. run your php file in browser, copy the entire response on the JSON validator and check the brackets that you are receiving the response in.
1. If your response starts with '[' it is and array and if it starts with '{' it is a JSON Object. while parsing JSON you have defined JSON array first but the server response is JSON object. While using JSON you have to be careful on server side for the format of response it will send and you have to be careful on the client side for the format of response you receive. I am posting example script for you.
-> Server side
if (mysql_num_rows($result)>0){
$response["data"] = array(); //this is an array
while($row= mysql_fetch_array($result))
{
$data = array(); //here I have created another temp array
$data["name"] = $row["name"];
$data["surname"] = $row["surname"];
array_push($response["data"], $data); //this makes an array of objects in the response
}}
}//endif
else{
echo "no input";
}}
mysql_close();
echo json_encode($response); //and finally I echo it as an JSON object
As this php script will return me one object of array of objects ( bit complex isn't it!!) below is the format of response
-> validated JSON response
{
"data": [
{
"name": "Setu",
"surname": "Desai",
}
]
}
and to decode this my client site script need to be the following
-> parsing JSON object
JSONObject snObject = new JSONObject(jsonString);
JSONArray snArray = snObject.getJSONArray("data");
for (int i = 0; i < snArray.length(); i++) {
JSONObject snObject2 = snArray.getJSONObject(i);
String surname = snObject2.getString("surname");
surnamearray.add(surname);
}
the simple way to understand is to validate you JSON response and identify the position of JSON array and objects and then start decoding.

Categories