How to create JsonArray and JsonObject in JsonObject java - java

How to create JsonArray and JsonObject in JsonObject
{
"users": [7, 16, 35],
"group_id": "askskdjejs139d.."
}
Thank for your help :)

You can try the following code:
JSONObject user1 = new JSONObject();
try {
user1.put("user_id", "7");
user1.put("group_id", "askskdjejs139d");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("user_id", "16");
user2.put("group_id", "askskdjejs139d");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(user1);
jsonArray.put(user2);
JSONObject userObj = new JSONObject();
userObj.put("Users", jsonArray);
String jsonStr = userObj.toString();
System.out.println("jsonString: "+jsonStr);

You can do this using org.json Library.
Given below are some examples:
// Creating a json object
JSONObject jsonObj = new JSONObject();
// Adding elements to json object
jsonObj.put("key", "value"); // the value can also be a json object or a json array
// Creating a json object from an existing json string
JSONObject jsonObj = new JSONObject("Your json string");
// Creating a json array
JsonArray jsonArray = new JsonArray();
// Adding a json object to json object to json Array
jsonArray.add(jsonObj);
// Adding json array as an element of json object
jsonObject.put("key", "<jsonArray>");
You can call toString() method of JsonObject or JsonArray to get the String representation of the json object/array.

Related

How to call JsonArrayRequest(response is an object array) for POST Method with a jsonobject body [duplicate]

This question already has answers here:
Volley Post request ,Send Json object in Json array request
(5 answers)
Closed 4 months ago.
My service response is a JsonArray but Body was I sent should be a jsonObject. But When I tried, It does not accept postData(it makes underlined as red in request line) So how can I solve that?
My service data comes but IT goes to onErrorResponse function when I use JsonobjectRequest and gives that error : com.android.volley.ParseError: org.json.JSONException: Value[{"total":120, ....}]
and in console detail message is : Value[{"total":120, ....}]of type org.json.JSONArray cannot be converted to JSONObject
Code is Like that:
GetDataFromService()
{
JSONArray xClasses = new JSONArray();
JSONArray xTypes = new JSONArray();
JSONArray xGroups = new JSONArray();
JSONArray yTypes = new JSONArray();
JSONObject filteredItems = new JSONObject();
try {
filteredItems.put("level", 0);
filteredItems.put("subLevel", 0);
filteredItems.put("id", 0);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject postData = new JSONObject();
try
{
postData.put("FilteredItems", filteredItems);
postData.put("XClasses", xClasses);
postData.put("XTypes", xTypes);
postData.put("XGroups", xGroups);
postData.put("YTypes", yTypes);
}
catch (JSONException e)
{
e.printStackTrace();
}
JsonArrayRequest postRequest = new JsonArrayRequest(Request.Method.POST, url, postData,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
try {
JSONArray json = new JSONArray(response);
System.out.println(json);
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
System.out.println(response); }
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
)
{ // Bearer Token - for Authorization
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("Authorization","Bearer " + token);
return params;
}
};
myQueue.add(postRequest);
}
Code gives an error for postData's Type. Because I send request as jsonarray but post data is jsonbject.
The JsonArrayRequest constructror accept a JSONArray as argument.
Try to convert your JSONObject to a JSONArray

How to encode jsonArray when added to jsonobject before sending to server using httpsurlconnection

I am getting the contact list from android and I want to send it to the server using HTTP URL connection. But every time, the added array to the jsonobject at the end, show up in string double quotes. How do I encode jsonobject, when it has jsonArray inside?
ArrayList<JSONObject> maps = new ArrayList<>();
String result ="";
try {
for (int i = 0; i < contactDetails.size(); i++) {
String FIRSTNAME =contactDetails.get(i).firstName;
String LASTNAME = contactDetails.get(i).lastName;
String CONTACT = contactDetails.get(i).contactNumber;
String EMAIL = contactDetails.get(i).email;
JSONObject contact = new JSONObject();
contact.put("firstName",FIRSTNAME );
contact.put("lastName",LASTNAME );
contact.put("contactNumber",CONTACT );
contact.put("email", EMAIL);
maps.add(contact);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject mainContact = new JSONObject();
try {
mainContact.put("token",token);
mainContact.put("contact",maps.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mainContact;
}
You have to use GSON library to make it in a easy way
Something like this
ArrayList<String> mArrayList = new ArrayList<String>();
mArrayList.add("First");
mArrayList.add("Second");
mArrayList.add("Third");
mArrayList.add("Fourtrh");
mArrayList.add("Fifth");
mArrayList.add("Sixth");
Log.i("Raw ArrayList", mArrayList);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
String JSONObject = gson.toJson(mArrayList);
Log.i("Converted JSONObject",JSONObject);
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = prettyGson.toJson(mArrayList);
Log.i("Pretty JSONObject",prettyJson);

Android - org.json.simple.JSONObject cannot be cast to org.json.JSONObject

I am trying to sort scores coming from a JSONArray and output only the top 10. Here is my code.
try {
JSONArray jArray = new JSONArray(result);
List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++)
jsonValues.add(jArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);
for(int i=0;i<10;i++){
JSONObject jObject;
try {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse((String) sortedJsonArray.get(i));
Score score =new Score();
score.setId(obj.getInt("Id"));
score.setPlayerId(obj.getInt("PlayerId"));
score.setHiScore(obj.getInt("HiScore"));
tempList.add(score);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I wanted to parse the sortedJsonArray into JSONObject that's why I used org.json.simple.JSONObject, but It says it cannot be cast to JSONObject. I tried using org.json.simple.JSONObject datatype for obj but I got this error
The method getInt(String) is undefined for the type JSONObject
I am retrieving data from a web server
List<Score> tempList = new ArrayList<Score>();
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(EndPoint+"/Scores");
String result="";
HttpResponse response;
try {
response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
if(entity!=null){
InputStream instream = entity.getContent();
StreamConverter sc= new StreamConverter();
result= StreamConverter.convertStreamToString(instream);
instream.close();
}
EDIT
I realized that I could just parse JSONArray to string using (String) and not use JSONParse. -____-
jObject = new JSONObject((String) sortedJsonArray.get(i));
Try this for parsing :
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
preDefineAlertList = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("Data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> mapNew = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// Log.d("obj", obj.toString());
alert_message = obj.getString(Constants.Params.MESSAGE);
id = obj.getString(Constants.Params.ID);
mapNew.put("message", message);
mapNew.put("id",id);
// Log.d("mapNew", mapNew.toString());
preDefinetList.add(mapNew);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
you are using the JSONObject of a library which uses Default JSONObject and does some manipulations to it.
You are using the JSONObject of that library from the package of simple.Jsonobject and you are trying to compare it to default json.Jsonobject .
Try yo see what exactly you are doing to cause it . It will help you not just in this case but in future as well.

Java volley empty json object

On a response I expect a JSON string.
But now I have to provide a key for the Object I want to retrieve. The response I want is just simple {"xx":"xx","xx":"xx"} format, without an array with a name like this {"XX":["xx":"xx"]}. How can I fetch the JSON without having to provide a parameter. In short, I just want to read the JSON response I get without having to give a parameter.
protected JSONObject parseJSONMeth() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject jo = users.getJSONObject(0);
return jo;
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
Why don't you use the GSON https://sites.google.com/site/gson/gson-user-guide :
Gson gson = new GsonBuilder().create();
User result = new User();
result=(gson.fromJson(json, User .class));
And for users List :
private static List<User> getDataFromJson(String json) {
Gson gson = new GsonBuilder().create();
List<User> result = null;
try {
JSONObject posts=new JSONObject(json);
result = gson.fromJson(posts.toString(), new TypeToken<List<User>>(){}.getType());
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}

json from java with multiple values

I have to send a json string to a server, with this sintax:
"id":"00",
"action":"register",
"get_value":"true",
"values":{
"user":"Jack",
"password":"Jhonson",
"id":"123456"
}
};
I have some problems with the values field, I don't know how to set them in a http request.
can someone makes me an example to how send this json string to a server?
thanks!
try {
JSONObject myObject = new JSONObject();
myObject.put("id", "00");
myObject.put("action", "register");
myObject.put("get_value", "true");
JSONObject values = new JSONObject();
values.put("user", "Jack");
values.put("password", "Jhonson");
values.put("id", "123456");
myObject.put("values",values);
} catch (JSONException e) {
e.printStackTrace();
}
Then use myObject.toString(); to send the content to the server
Please set this json in httpPost.setParams(your_jsonstring);
Prepare Json Object from data :
try{
JSONObject mainJsonObject = new JSONObject();
mainJsonObject.put("id", "00");
mainJsonObject.put("action", "register");
mainJsonObject.put("get_value","true");
JSONObject valueJsonObject = new JSONObject();
valueJsonObject.put("user", "Jack");
valueJsonObject.put("password", "Jhonson");
valueJsonObject.put("id","123456");
mainJsonObject.put("value",valueJsonObject);
}catch (JSONException e){
e.printStackTrace();
}
Add json data to StringEntity as String:
StringEntity se = new StringEntity(mainJsonObject.toString());
Set StringEntity to httpPost :
httpPost.setEntity(se);

Categories