json from java with multiple values - java

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);

Related

How to create JsonArray and JsonObject in JsonObject 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.

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;
}

creating complex JSON using BasicNameValuePair

How can I create this JSON using ArrayList for posting json in Android
{
"user" :
{
"nickname" : "nickname6",
"password" : "1234",
}
}
I get only to a flat JSON
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nickname","nickname6"));
nameValuePairs.add(new BasicNameValuePair("password", "1234"));
You need to create a JSON, and for that you have to add that JSON as a parameter in your POST method. To do that you can try this :
JSONObject json = new JSONObject(jsonString);
JSONObject joParams = json.getJSONObject("params");
String nickname = joParams.getString("nickname");
post.add(new BasicNameValuePair("nickname", nickname);
As you know, HttpClasses, NameValuePair and BasicNameValuePair have been deprecated in latest android. we should avoid it now.
and If you want to create
{
"user":{
"nickname":"nickname6"
"password":"1234",
}
}
Than you can use below code sample to create the same json using JSONObject class.
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
} catch(Exception e) {
e.printStackTrace();
}
try to use ContentValues like this way
ContentValues values=new ContentValues();
values.put("username",name);
values.put("password",password);
OR
Use MultipartEntity
MultipartEntity multi = new MultipartEntity();
multi.addPart("name", new StringBody("your data"));
multi.addPart("Id", new StringBody("123"));
here's an example for http post using AsyncTask:
public class httpSendrequest extends AsyncTask<Void,Void,String> {
ArrayList<NameValuePair> nvPairs=new ArrayList<>();
Boolean error=false;
#Override
protected void onPreExecute() {
super.onPreExecute();
//here you initialize your json object and add it to value pairs
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
nvPairs.add(new BasicNameValuePair("jsonstring",jObj.toString()));
} catch(Exception e) {
error=true;
}
}
#Override
protected String doInBackground(Void... params) {
if(!error)
try{
String link ="http://"+ip+"/QSystem.asmx/insert_answer" ;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link); //adding URL to the http post
httppost.setEntity(new UrlEncodedFormEntity(nvPairs, HTTP.UTF_8)); //adding the value pairs and encoding to the http post request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e){
error=true;
}
return "str";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(!error) {
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}
}
then you can call it from onCreate or in an OnClickListener for a button, like this:
new httpSendrequest().execute();
hope this helps :)

How to call a json webservice through android

I need to access a .Net web service in Rest format using JSON. I m
pretty new to this concept and very much confused about how this
works....
Any one who can give an overview of this. I need the steps that I
need to follow to use JSON. Right now my doubt is how to use JSON to
grab to output.
This is the simplest way to parse Json web servie
String str="url";
try{
URL url=new URL(str);
URLConnection urlc=url.openConnection();
BufferedReader bfr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line;
while((line=bfr.readLine())!=null)
{
JSONArray jsa=new JSONArray(line);
for(int i=0;i<jsa.length();i++)
{
JSONObject jo=(JSONObject)jsa.get(i);
title=jo.getString("deal_title"); //tag name "deal_title",will return value that we save in title string
des=jo.getString("deal_description");
}
}
catch(Exeption e){
}
Mention Internet permission in android manifest
Gson library can parse your json string automatically to object.
Simple example:
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
//(Serialization)
gson.toJson(ints); ==> prints [1,2,3,4,5]
gson.toJson(strings); ==> prints ["abc", "def", "ghi"]
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
==> ints2 will be same as ints
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
you use the json data as follows:
var a=new JSONObject(jsonData);
http://developer.android.com/resources/tutorials/views/hello-mapview.html
Use the data from a to constuct the necessary objects and do the necessary with the same

Categories