I want to construct a JSON payload of this:
{
"aps": {
"badge": 15,
"alert": "Hello from Urban Airship!",
"sound": "cat.caf"
}
}
I tried with this thing :
JSONObject json = new JSONObject();
JSONObject badge=new JSONObject();
JSONObject alert=new JSONObject();
JSONObject sound=new JSONObject();
badge.put("badge",15);
json.put("aps",badge);
sound.put("sound",getResources().openRawResource(R.raw.cat));
json.put("aps",alert);
alert.put("alert", "Hello from Uday!");
json.put("aps",sound);
but it full payload is obtaining:when I print
am getting like half of payload like this:
{"aps":{"sound":"cat.caf"}}
its overriding, but
How do it in a correct way
Thanks
I am not sure what you are looking for, but considering that you want to create a JSON String.
try {
JSONObject json = new JSONObject();
JSONObject aps = new JSONObject();
aps.put("badge", 15);
aps.put("alert", "Hello from Urban Airship!");
aps.put("sound", "cat.caf");
Log.d("my json string", json.put("aps", aps).toString(1));
} catch (JSONException e) {
e.printStackTrace();
}
openRawResource() returns an InputStream.. you might want to try reading it using an InputStreamReader?
Related
I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's.
I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.
The code I have been using for json object is
obj = parser.parse(new FileReader("path of json"));
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
This code gives class cast exception at
jsonObject = (JSONObject) obj; when I pass a json array.
Kindly help me with the same
This is the JSON Array
[
{
"findingId": "20177044",
"unsupressAfterDuration": 1669968369043,
"developer": "manan.girdhar#armorcode.io",
"kbIds": [],
"ticketConfigurationId": "3350",
"customFields": []
}
]
Your parser parses the part of JSON and probably returns a JSONArray, but you are casting it to JSONObject. Maybe you want to use something like
obj = parser.parse(new FileReader("path of json"));
if (obj instanceof JSONObject) {
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
} else {
throw new Exception("We do not know how to handle non-objects like " + obj.getClass().getName());
// replace this with list-handling code
}
If you want only one code fragment to handle both objects and lists, cast to JsonStructure.
answering my own question as I found a solution
JSONArray array1 = new JSONArray();
data1.put("findingId", findingIdFinal);
data1.put("unsupressAfterDuration", "1669968369043");
data1.put("developer","manan.girdhar#armorcode.io");
data1.put("kbIds",array1);
data1.put("ticketConfigurationId", jiraId);
data1.put("customFields",array1);
array.put(data1);
String jsonString = array.toString();
List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);
response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);
I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
I'm using Google Play Games Snapshot and I have to pass in the data I need to save by using JSON.
Here is the JSON file:
{"Date":1531043635316,"Daily bonus":2,"sound enabled":true,"total coins":2099300,"high score":0,"Btns Set":1,"leftBtnX":46,"leftBtnY":18,"leftBtnsize":1,"upBtnX":105,"upBtnY":18,"upBtnsize":1,"rightBtnX":164,"rightBtnY":18,"rightBtnsize":1,"guardBtnX":288,"guardBtnY":18,"guardBtnsize":1,"chargeBtnX":363,"chargeBtnY":18,"chargeBtnsize":1,"attackBtnX":438,"attackBtnY":18,"attackBtnsize":1,"superBtnX":438,"superBtnY":58,"superBtnsize":1,"ultimateBtnX":363,"ultimateBtnY":58,"ultimateBtnsize":1,"dpadX":80,"dpadY":40,"dpadSize":1,"gpadX":405,"gpadY":59,"gpadSize":1}
Now when I try to change only one of them using this code:
private byte[] saveToJSON(){
try {
JSONObject obj = new JSONObject();
obj.put("total coins", Settings.totalCoins);
return obj.toString().getBytes();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("Error converting save data to JSON.", e);
}
}
The entire file get's changed to only this single parameter, it becomes this:
{"total coins":2099300}
Now how Can I just modify a single parameter value?
Sorry, this is the first time for me to work with JSON
JSONObject obj = new JSONObject(); make you create a new json object,that's the reason,you can change to below code:
String jsonStr = "";//your json string
JSONObject obj = new JSONObject(jsonStr);
obj.put("total coins", Settings.totalCoins);
My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);
1) I've got a JSON file:
{
"serverURI":"http://localhost:8080/PocketUNI_API/serverURLs",
"newsURI":"http://localhost:8080/gateway/rss/rss.xml",
"modulesURI":"http://localhost:8080/PocketUNI_API/modules"
}
2) I need to get URLs on Java client in String format.
String json = jsonReceiver.makeHttpRequest(URL_SERVER, "GET", params);
JSONArray uris = new JSONArray(json);
Receiver works fine and json shows the correct string received, but when it goes to parsing with JSONArray it throws an error
org.json.JSONException: Value {"serverURI":"http:\/\/192.168.0.... of type org.json.JSONObject cannot be converted to JSONArray.
Question: How to parse json with URL values?
You don't get a JSONArray but a JSONObject.
JSONObject uris = new JSONObject(json);
json is a json object not an array, that is why you are getting the error. An array will be wrapped with in [ and ], and objects within { and }.
JSONObject uris = new JSONObject (json);
Instead of JSONArray you must use JSONObject.
JSONObject uris = new JSONObject(json);
In your code just replace JSONArray to JSONobject
JSONObject uris = new JSONObject(json);