I have this JSON file that I would like to send to a server with POST
{
"header1" : {
"message" : {
"content" : "Hello",
"type" : "text"
},
"header2" : {
"address" : "sample#example.com"
}
}
}
This is the code I have for the json pbject
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", "hello");
jsonObject.put("type", "text");
jsonObject.put("address", "sample#example.com");
String message = jsonObject.toString();
My question is how do I code the hierarchy: header1, message and header2?
JSONObject json = new JSONObject();
JSONObject messageObject = new JSONObject();
JSONObject header2Object = new JSONObject();
try {
messageObject .put("content", "Hello");
messageObject .put("type", "text");
header2Object .put("address", "sample#example.com");
json.put("header1", messageObject.tostring);
json.put("header2", header2Object.tostring );
} catch (Exception ignored) {
}
Try This
I think you should do this in a bottom up fashion.
What I mean is first make a JSONObject with the name header2 and put address in it.
Then make the other JSONObject named message, populate it using put and then in turn place it inside another JSONObject named header1.
JSONObject header2 = new JSONObject ();
header2.put("address", "your address");
Then,
JSONObject header1 = new JSONObject ();
header1.put("header2", header2);
And so on...
Related
Hi guys i got a json string like
{
"Successful": true,
"Value": "{\"MesajTipi\":1,\"Mesaj\":\"{\\\"Yeni\\\":\\\"Hayır\\\",\\\"Oid\\\":\\\"3d9b81c9-b7b3-4316-8a73-ad4d54ee02a8\\\",\\\"OzelKod\\\":\\\"\\\",\\\"Adet\\\":1,\\\"ProblemTanimi\\\":\\\"999\\\",\\\"HataTespitYeri\\\":\\\"Montajda\\\",\\\"Tekrar\\\":\\\"Evet\\\",\\\"ResmiBildirimNo\\\":\\\"\\\",\\\"Malzeme\\\":\\\"5475ffdb-0bc0-49cb-9186-429c60dbf91b\\\",\\\"HataKodu\\\":\\\"c30df623-496b-4a62-ba16-493bd435ca33\\\",\\\"Tarih\\\":\\\"2016-04-16 10:34:00\\\",\\\"KayitNo\\\":\\\"1600010.2\\\"}\"}"
}
I need to get "Oid" value from this string.
I tried to get it with
Gson gson = new Gson();
JsonParser parse = new JsonParser();
JsonObject jsonobj = (JsonObject) parse.parse(snc);
String stroid = jsonobj.get("Oid").toString();
But it gives null referance exception ? Any idea how can i get the only Oid value ?
Edit
I already tried How to parse JSON in Java but still no succes
What i tried from this page :
String pageName = jsonObj.getJSONObject("Value").getJSONObject("Mesaj").getString("Oid");
lets say this is your JSON
{
"success":"ok",
"test" : [{"id" : "1" ,"name" : "first"}]
,"RPTF":
[{"cats":[{"id" : "1" ,"name" : "first"},
{"id" : "1" ,"name" : "first"},
{"id" : "2" ,"name" : "test"} ]
,"pics" : [{"id" : "12" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" },
{"id" : "10" ,"value" : "description" ,"src" : "http://citygram.ir" ,"visit" : "3" } ]
}]
}
method number one (if you want to access "success")
public String jsonOne(String json, String target) {
String result;
try {
JSONObject jo = new JSONObject(json);
result = jo.getString(target);
} catch (JSONException e) {
return "";
}
return result;
}
you can simply call this method like this
jsonOne(String json, "success");
method number two (in case you want to access "id"s inside the "test")
public String[] jsonTwo(String json, String target0, String target1) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
result = new String[ja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojo = ja.getJSONObject(i);
result[i] = jojo.getString(target1);
}
} catch (JSONException e) {
}
return result;
}
you get an array String on call :
jsonTwo(String json, "test", "id");
method number three (let's say you want to access "value"s in side "pics")
public String[] jsonThree(String json, String target0, String target1,String target2) {
String[] result;
result = new String[1];
try {
JSONObject jo = new JSONObject(json);
JSONArray ja = jo.getJSONArray(target0);
JSONObject jojo=ja.getJSONObject(0);
JSONArray jaja=jojo.getJSONArray(target1);
result = new String[jaja.length()];
for (int i = 0; i < ja.length(); i++) {
JSONObject jojojo = jaja.getJSONObject(i);
result[i] = jojojo.getString(target2);
}
} catch (JSONException e) {
toast("Wrong");
}
return result;
}
on call :
jsonThree(String json, "RPTF", "pics", "value");
you can write more methods like this and just call them .
The problem is because of extra " " in the "Value" section of JSON, so it will be treated as String not an object. The better solution is to seek the source of the JSON to see why they added extra " " and clear that but if you don't have access the source I propose the following:
Replace:
String stroid = jsonobj.get("Oid").toString();
with:
String valueString = jsonobj.getString("Value");
jsonobj = new JSONObject(valueString);
String mesagString = jsonobj.getString("Mesaj");
jsonobj = new JSONObject(mesagString);
String stroid = jsonobj.getInt("Oid").toString();
I have request something like this.
{"REQ_DATA":
{"CLPH_NO":"010123456789","USE_INTT_NO":""}
}
but server accepts only this
{"REQ_DATA":
[{"CLPH_NO":"010123456789","USE_INTT_NO":""}]
}
What should I do? I quite noob about JSON, please help me.
REQ_DATA needs to be a JSONArray. Try implementing something like this
try {
JSONObject object = new JSONObject();
JSONArray requiredDataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put("CLPH_NO", "010123456789");
data.put("USE_INTT_NO", "");
requiredDataArray.put(data);
object.put("REQ_DATA", requiredDataArray);
Log.d("JSON", object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
You can try:
JSONObject fromRequest = request.getJSONObject();// given from request
JSONObject toServer = new JSONObject();
JSONArray arr = new JSONArray();
arr.put(fromRequest.get("REQ_DATA"));
toServer.put("REQ_DATA", arr);
Jsonarray array = new Jsonarray();
Jsonobject insidearray = new jsonobject;
insidearray.put("CLPH_NO", "010123456789");
insidearray.put("USE_INTT_NO", "");
array.put(insidearray);
Jsonobject object = new Jsonobject();
object.put("REQ_DATA",array);
The variables may need a little editing, doing this from a phone but there you go
You don't change a JSONObject to a JSONArray, rather, you create a JSONArray and then add the JSONObject to that array.
try {
JSONObject reqData = new JSONObject();
reqData.put("CLPH_NO", "010123456789");
reqData.put("USE_INTT_NO", "");
JSONArray array = new JSONArray();
array.put(reqData);
JSONObject request = new JSONObject();
request.put("REQ_DATA", reqData);
String requestAsJSONString = request.toString();
// call web service
} catch (JSONException e) {
// handle exception
}
You need to send requestAsJSONString to the server.
Furthermore, I suggest you put the JSON object keys in final fields, like so:
static final String KEY_REQ_DATA = "REQ_DATA";
and then use KEY_REQ_DATA in your code instead of using the hardcoded String.
This is simple solution for your json string as per server check it
JSONObject jo = new JSONObject();
try {
jo.put("CLPH_NO", "010123456789");
jo.put("USE_INTT_NO", "");
} catch (Exception e) {
}
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject final_jo = new JSONObject();
try {
final_jo.put("REQ_DATA", ja);
} catch (Exception e) {
}
Toast.makeText(getApplicationContext(),final_jo.toString(),Toast.LENGTH_LONG).show();
Just simple solution without using any hard-coded Strings
JSONObject currentJson = new JSONObject(yourJsonString); //Your current jsonObject
JSONObject newJsonObject = new JSONObject(); //new jsonObject you want to send to server
newJsonObject.put(currentJson.keys().next().toString(),
new JSONArray().put(currentJson.getString(currentJson.keys().next().toString())));
I want to send Json Parameters (below) in Android - POST Method.
{"message":"This is venkatesh","visit":[5,1,2]}
I tried the below code
String IDs="5,1,2";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(IDs);
jsonObject.put("visit", jsonArray);
String json = jsonObject.toString();
Log.d("Mainactivity", " json" + json);
I am getting the output is
{"message":"This is venkatesh","visit":["5,1,2"]}
// Output i am get with double quotes inside visit
{"message":"This is venkatesh","visit":[5,1,2]}
// I want to send this parameter without Double quotes inside the Visit
String IDs="5,1,2";
String[] numbers = IDs.split(",");
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < numbers.length(); i++)
{
jsonArray.put(Integer.parseInt(numbers[i]));
}
Hope this helps.
In array add it as integer not as a String
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(5);
jsonArray.put(1);
jsonArray.put(2);
jsonObject.put("visit", jsonArray);
String json = jsonObject.toString();
Log.i("TAG", " json" + json); //{"message":"This is venkatesh","visit":[5,1,2]}
} catch (JSONException e) {
e.printStackTrace();
}
Just replace following line:
jsonArray.put(IDs);
with following code:
jsonArray.put(5);
jsonArray.put(1);
jsonArray.put(2);
So you should use 'int' values if you want to see array without quotes. The point is 'quotes' means that this is String object. Proof is following line of your code:
String IDs="5,1,2";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray(new int[](5, 1, 2));
jsonObject.put("visit", jsonArray);
I am assuming you will convert the String to integer array and after you do this is how you can add,
Well the only difference you need to understand is that, JSON adds double quotes for values of String and not of Integer.
so for Key value pair for String it would be
"key":"value"
so for Key value pair for Integer it would be
"key":123
so for Key value pair for boolean it would be
"key":true
With that knowledge you can edit your code.
Code
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(0,5);
jsonArray.put(1,1);
jsonArray.put(2,2);
jsonObject.put("visit", jsonArray);
Log.d("TAG","result "+jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
Output
{"message":"This is venkatesh","visit":[5,1,2]}
int[] arrayOfInteger=[1,2,3];
JSONObject jsonObject =new JSONObject();
jsonObject .put("message","your message");
JSONArray jsonArray = new JSONArray(arrayOfInteger);
jsonObject .put("visit",jsonArray );
Result : {"message":"your message","visit":[1,2,3]}
I want to send the following parameter
data={"method": "category", "parameter": {"id":20, "language":"en"}}
to a web service
How can I do this from android for get method?
i tried but did not work.
your JSON is created like this :
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "category");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", 20);
jsonObject1.put("language", "en");
jsonObject.put("parameter",jsonObject1 );
} catch (JSONException e) {
e.printStackTrace();
}
Now you can add this in your request with key as "data"
try this
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",20 );
jsonObject.put("language","en");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("method", "category");
jsonObject2.put("parameter", jsonObject.toString());
I am creating json string but unable to give tag to JSONObject in nested json string.
Here is what I want
"User": [
{
"User1": {
"name": "name1",
"Address": "add1",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
},
{
"User2": {
"name": "name2",
"Address": "add2",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
}
}
]
And I have managed to get until here
{"User":[{"name":"name1","Address":"Add1"}, {"Qualification": "B.E", "DOB":"11/12/1990"}]}
But I am failed to add tag for JSONObject both for USer and user_details
Here is my code
try {
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
} catch (JSONException je) {
je.printStackTrace();
}
try {
userObj = new JSONObject();
userObj.put("User1", user);
jsonArray = new JSONArray();
jsonArray.put(user);
} catch (JSONException j) {
j.printStackTrace();
}
}
try {
users = new JSONObject();
users.put("User", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
The main thing is I am do not know, how to give tags to JSONObject.
You could just pass the desired JSON String to the JSONObject constructor to do the job. Take a look here
Current String Contain JSONArray of JSONObject's instead of JSONObject as root element. You can create Current Json String in java as:
JSONArray jsonArray = new JSONArray();
// User1 JSONObjects
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
user_obj_one = new JSONObject();
user_obj_one.put("User1",user);
//...same for User2...
...
user_obj_two = new JSONObject();
user_obj_two.put("User2",user_two);
//put in final array :
jsonArray.put(user_obj_one);
jsonArray.put(user_obj_two);
//....