Sending only one string as parameter to JsonObjectRequest (NOT key-value) - java

I need to pass a String as a parameter in the following format: ["default"]
How should I build my JSONObject in order to do:
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url, jsonObject, new Response.Listener<JSONObject>() {
...
}
I've tried:
String modeParam = "[\"" + mode.toLowerCase() + "\"]";
final JSONObject jsonObject = new JSONObject();
jsonObject.put("", modeParam);
Is there another way to send just a String? 'Cause it would be great if I could avoid using a map since it's not what I need for this type of body.
Update, Ive tried this as well:
JSONArray jarray = new JSONArray();
jarray.put(mode.toLowerCase());
final JSONObject jsonObject = new JSONObject();
jsonObject.put("", jarray);

Add the body text to JSONArray:
JSONArray jarray = new JSONArray();
jarray.put("default");
And you will have an array with size = 1.

I ended up doing this:
(basically ended up doing ajsonarrayrequest instead)
JSONArray jarray = new JSONArray();
jarray.put(mode.toLowerCase());
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.PUT, url, jarray, new Response.Listener<JSONArray>() {
....

Related

Json object to java arraylist

I have pass two values from ajax to my servlet.
I used
JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
and this is the output
{"0":"31/01/2017","1":"19/01/2017"}
Now I want to convert this data into a java arraylist but not really sure how.
I tried
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray();
// jsonArr.
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
But got an error
java.lang.IllegalStateException: This is not a JSON Array.
Someone help me please? thanks.
Create instance of JsonArray then add json element to that array using key.
Here is your solution :
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson(request.getReader(), JsonObject.class);
System.out.println(data);
JsonArray jsonArr = new JsonArray();
for(Entry<String, JsonElement> entry : data.entrySet()) {
jsonArr.add(data.get(entry.getKey()));
}
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i = 0; i < jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
For a Json to be a valid JsonArray object you should have it to a proper format. Can you change your json string return from your ajax? If yes you should change it to something like this:
Gson googleJson = new Gson();
JsonObject data = googleJson.fromJson("{test: [{\"0\":\"31/01/2017\"},{\"1\":\"19/01/2017\"}]}", JsonObject.class);
System.out.println(data);
JsonArray jsonArr = data.getAsJsonArray("test");
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
for(int i=0; i< jsonObjList.size(); i++) {
System.out.println(jsonObjList.get(i));
}
If not you should parse it by your self and convert it to everything you want.

parse and get specific field from HTTP response in java

I try to parse a HTTP response to a JSONObject and retrieve some fields, coould be a String or int.
My response is a json array like this:
[{nid: "24161",changed: 1445936169,created: "1444728767",language: "en",status: 1,title: "bicycle",type: "product",uid: "2172",vid: "24161"}]
And I tried using:
JSONObject myObject = new JSONObject(response);
And gson , still after parsing the response turns to {}.
Thanks for any help.
You must use JSONArray instead of JSONObject
JSONArray array = new JSONArray(response);
You can then iterate throw the array and get the fields you want
for(int i=0; i<array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String nid = object.getString("nid");
int changed = object.getInt("changed");
//...
}
You are parsing json array into object. Use JSONArray instead of JSONObject
JSONArray myArray = new JSONArray(response);
you can get your object by index from your array.

How to create a dynamic JSONObject?

I have a little problem
I've write a code that create an object from JSONObject and add some data on it like this:
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject1 = new JSONObject();
innerObject1.put("id", "semantic web");
innerObject1.put("url", "www.semanticweb.com");
innerObject1.put("definition", "this is the denfition of semantic web");
outerArray.put(innerObject1);
then I create another one called innerObject2 and do the same process like this:
JSONObject innerObject2 = new JSONObject();
innerObject2.put("id", "ontology");
innerObject2.put("url", "www.ontology.com");
innerObject2.put("definition", "this is the denfition of ontology");
outerArray.put(innerObject2);
outerObject.put("rows", outerArray);
return outerObject.toString();
the results will be some thing like this:
{"rows":[{"definition":"this is the denfition of semantic web","id":"semantic web","url":"www.semanticweb.com"},{"definition":"this is the denfition of ontology","id":"ontology","url":"www.ontology.com"}]}
My problem is: what if I want to create another JSONObject called innerObject3 , innerObject4 , innerObject5 .... etc using for loop?
any suggestions?
thanks for your response
I've manage to solve this problem as follow:
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject [] innerObject = new JSONObject[4];
for(int i =0; i<3; i++)
{
innerObject[i]=new JSONObject();
innerObject[i].put("id", "id of "+i);
innerObject[i].put("url", "url of "+i);
innerObject[i].put("Definition", "Definition of "+i);
outerArray.put(innerObject[i]);
}
outerObject.put("rows", outerArray);
return outerObject.toString();
hope that this can help others :)

Java:how to parse this json

I want to parse this json to retrieve the value of tel or user_id
For example:
{
"status":"ok",
"account":{
"0":{
"user_id":"2",
"thirdparty_id":"200",
"tel":"28000000",
"mobile":"28000000",
"fax":"28000000"
}
}
}
Here is the code I am attempting to use to retrieve tel:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
JsonObject rootobj1 = (JsonObject) rootobj.get("account");
JsonObject rootobj2 = (JsonObject) rootobj.get("0");
String tel=rootobj2.get("tel").getAsString();
The problem is that a java.lang.NullPointerException is thrown at this line :
String tel=tel=rootobj2.get("tel").getAsString();
First thing if you have post the JsonString correctly then it is not a valid json as tel" should be "tel"
Then you can parse it using org.json as
JSONObject jsonObject = new JSONObject(str);
JSONObject json1 = new JSONObject(jsonObject.get("account").toString());
JSONObject json2 = new JSONObject(json1.get("0").toString());
System.out.println(json2.get("user_id").toString());
You have two problems. First, you are not actually descending the tree. Initialize rootobj2 like this:
JsonObject rootobj2 = (JsonObject) rootobj1.get("0"); // NOT rootobj.get("0");
Second, once rootobj2 is initialized correctly, it will not have an attribute "0". Try this:
String tel=rootobj2.get("tel").getAsString(); // NOT rootobj2.get("0").getAsString();

Json Iterating using java

Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.

Categories

Resources