How do i get, modify and post a json object? - java

as mentioned in my older topic 3 days ago - Last Topic
i got a json response and changed it to a string. The Json Response represents an User-Object. Within the User-Object i wanted to search for a specific project and delete it. After that, i want to post it again via HttpPost.
private static String getContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity == null) return null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = reader.readLine();
reader.close();
return line;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
String StringResponse = getContent(JsonResponse);
JSONObject jsonObject = new JSONObject(StringResponse);
JSONArray ProjectsArray= jsonObject.getJSONArray("projects");
Searching for a specific project by saving the attributes in a JsonArray.
ArrayList<Integer> indexesToRemove = new ArrayList<Integer>();
for (int i = 0; i < projectsArray.length; i++) {
JSONObject current = projectsArray.get(i);
if (current.get("projectKey") == "**ProjectName**") {
indexesToRemove.add(i);
}
}
Deleting the project...
for (int i = indexesToRemove.size()-1; i>=0; i--)
{
projectsArray.remove(indexesToRemove.get(i));
}
That works perfect and my searched project is deleted. But the problem is, that i want to post the modified UserObject/String again via HttpPost. And my deleted project is just in my JsonArray "projectsArray" and not in my string from the beginning. I can't post "projectsArray"....
HttpPost UserChange = new HttpPost (TestUserURL+user); //TODO:
UserChange.setHeader("Accept", "application/json");
UserChange.setHeader("Content-type", "application/json");
params = new StringEntity("ModifiedJsonString", HTTP.UTF_8); // How do i get the complete Json string?
UserChange.setEntity(params);
HttpResponse UserChangeResponse = httpclient.execute(UserChange);
HttpEntity entity2 = UserChangeResponse.getEntity();
if (entity2 != null) {
entity2.consumeContent();
}
I need the "ModifiedJsonString", which includes the complete json file from the beginning.
params = new StringEntity(ModifiedJsonString, HTTP.UTF_8);
Best Regards

The following code removes one of the selected project.
String jsonString = "{ \"account\": \"Kpatrick\", \"firstname\": \"Patrick\", \"instances\": [ { \"id\": \"packerer-pool\", \"key\": \"packerer-pool123\", \"userAccount\": \"kpatrick\", \"firstname\": \"Patrick\", \"lastname\": \"Schmidt\" } ], \"projects\": [ { \"id\": \"packerer-projectPool\", \"projectKey\": \"projectPool-Pool\", \"cqprojectName\": \"xxxxx\" }, { \"id\": \"packerer-secondproject\", \"projectKey\": \"projectPool-Pool2\", \"cqprojectName\": \"xxxx\" }, { \"id\": \"packerer-thirdproject\", \"projectKey\": \"projectPool-Pool3\", \"cqprojectName\": \"xxxx\" } ], \"clients\": [], \"dbid\": 76864576, \"version\": 1, \"id\": \"dbpack21\"}";
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
ArrayList<String> listOfNodes = new ArrayList<String>();
JSONArray projectArray = (JSONArray) jsonObject.get("projects");
int len = projectArray.size();
if (projectArray != null) {
for (int i = 0; i < len; i++) {
String projectId = ((JSONObject) projectArray.get(i)).get("projectKey").toString();
if (!projectId.equals("projectPool-Pool2")) {
listOfNodes.add(projectArray.get(i).toString());
}
}
}
// Remove the element from arraylist
// Recreate JSON Array
JSONArray jsArray = new JSONArray();
jsArray.addAll(listOfNodes);
jsonObject.remove(projectArray);
jsonObject.put("projects", listOfNodes);
System.out.println(jsonObject.toString());
This for example , prints the following JSON string removing one of the projects.
Once you have this , you can then use this to create a StringEntity and then use it in HTTPPost calls. Hope it helps

Related

JSONException on trying to get a value from Json to String

I'm trying to get 2 values from Wikipedia with the next API link:
https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8
because its generated by random, sometimes it doesn't return one of the values I need, but I will solve this later, currently I'm having a problem with accessing the two values I need in the Json, "title" and "source"
The returned Json is like this:
{"batchcomplete":"","continue":{"grncontinue":"0.360395277951|0.360395626487|10429617|0","continue":"grncontinue||"},"query":{"pages":{"38690716":{"pageid":38690716,"ns":0,"title":"Alaine Chartrand","thumbnail":{"source":"https://upload.wikimedia.org/wikipedia/commons/d/d4/Alaine_Chartrand.jpg","width":267,"height":400},"pageimage":"Alaine_Chartrand.jpg"}}}}
this is the code, can anybody figure out why does it go to JSONException?
String API = "https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8";
//open connection with wikipedia.
HttpURLConnection httpcon = (HttpURLConnection) new URL(API).openConnection();
//read all the input from wikipedia.
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
String responseSB = in.lines().collect(Collectors.joining());
in.close();
JSONObject incomingJSON = new JSONObject(responseSB);
//crashes here
String mTitle = incomingJSON.getString("title");
String mUrl = incomingJSON.getString("source");
If you notice the JSON it is randomly generated but with specific format
Case 1
{
"batchcomplete": "",
"continue": {
"grncontinue": "0.720220803439|0.720221273467|12887566|0",
"continue": "grncontinue||"
},
"query": {
"pages": {
"4897672": {
"pageid": 4897672,
"ns": 0,
"title": "New Hope, Sunnyvale, Texas"
}
}
}
}
query and pages were always existed, and in pages the key is always randomly generate, so it is Map<String, JSONObject> map of String key and JSONObject as value, Then you need to get the title value from map values
String API = "https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8";
//open connection with wikipedia.
HttpURLConnection httpcon = (HttpURLConnection) new URL(API).openConnection();
//read all the input from wikipedia.
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
String responseSB = in.lines().collect(Collectors.joining());
in.close();
JSONObject incomingJSON = new JSONObject(responseSB);
Map<String,JSONObject> map = (Map<String, JSONObject>) incomingJSON.getJSONObject("query").getJSONObject("pages");
map.forEach((k,v)->System.out.println(" The key is : "+k+" the title is : "+v.getString("title")));
Case 2 With source
{
"batchcomplete": "",
"continue": {
"grncontinue": "0.165621850014|0.165622038679|37982311|0",
"continue": "grncontinue||"
},
"query": {
"pages": {
"57529788": {
"pageid": 57529788,
"ns": 0,
"title": "Model Store",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/23/Australia_New_South_Wales_relief_location_map.png/500px-Australia_New_South_Wales_relief_location_map.png",
"width": 500,
"height": 443
},
"pageimage": "Australia_New_South_Wales_relief_location_map.png"
}
}
}
}
So source may not present in every response, handle with try catch
String API = "https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8";
//open connection with wikipedia.
HttpURLConnection httpcon = (HttpURLConnection) new URL(API).openConnection();
//read all the input from wikipedia.
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
String responseSB = in.lines().collect(Collectors.joining());
in.close();
JSONObject incomingJSON = new JSONObject(responseSB);
Map<String,JSONObject> map = (Map<String, JSONObject>) incomingJSON.getJSONObject("query").getJSONObject("pages");
map.forEach((k,v)->{
System.out.println(" The key is : "+k+" the title is : "+v.getString("title"));
//use try catch to get source because you will not get the same response every time
String source = v.getJSONObject("thumbnail").getString("source");
});
}
You can't get title and source directly from JSON response because it has to contain multiple inner objects. Below is the code snap for reading title and source.
// new code
JSONObject incomingJSON = new JSONObject(responseSB);
JSONObject innerObject = incomingJSON.getJsonObject("query").getJsonObject("pages").getJsonObject("38690716");
String mTitle= innerObject.getString("title");
String mUrl= innerObject.getJsonObject("thumbnail").getString("source");
//crashes here
String mTitle = incomingJSON.getString("title");
String mUrl = incomingJSON.getString("source");
try this...
JSONObject incomingJSON = new JSONObject(responseSB);
JSONObject TitleObjects = incomingJSON.getJSONObject("query");
JSONObject j_Objects_01 = TitleObjects.getJSONObject("pages");
JSONObject j_Objects_02 = j_Objects_01.getJSONObject("38690716");
String mTitle = j_Objects_02.getString("title");
JSONObject j_Objects_03 = j_Objects_02.getJSONObject("thumbnail");
String mUrl = j_Objects_03.getString("source");
You should be aware that the page id will change and the thumbnail is optional.
// new code
JSONObject incomingJSON = new JSONObject(responseSB);
JSONObject pages = incomingJSON.getJSONObject("query").getJSONObject("pages");
Iterator<String> it = pages.keys();
while(it.hasNext()) {
JSONObject page = pages.getJSONObject(it.next());
String mTitle= page.getString("title");
if(page.keySet().contains("thumbnail")) {
String mUrl= page.getJSONObject("thumbnail").getString("source");
}
}
So because the ID kept changing, I've decided to go from another approach.
I've used the following code:
Pattern p = Pattern.compile("\"source\":\"(.*?)\",\"width");
Matcher m = p.matcher(responseSB);
if (m.find()) {
url = m.group(1);
}
p = Pattern.compile("\"title\":(.*?)\",\"thumbnail");
m = p.matcher(responseSB);
if (m.find()) {
description = m.group(1);
}

JSONObject["name"] not a string

I've been trying for the last couple hours to fix this. I'm a little rusty when it comes to Java and decided I wanted to finish this method where I'm trying to parse the json to get the name of a map.
private static void mapLookUp (String mapId){
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://www.haloapi.com/metadata/h5/metadata/maps");
URI uri = builder.build();
HttpGetWithEntity request = new HttpGetWithEntity(uri);
request.addHeader("ocp-apim-subscription-key", "aa09014c153b4a4b9c3a4937356e208a");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
String response2request = EntityUtils.toString(entity);
//System.out.println(response2request.length()+"\n"+response2request);
String jsonString = "{\"Results\":"+response2request+"}";
System.out.println(jsonString);
JSONObject jsonResult = new JSONObject(jsonString);
List<String> mapName = new ArrayList<String>();
List<String> mapIds = new ArrayList<String>();
JSONArray array = jsonResult.getJSONArray("Results");
for(int i = 0 ; i < array.length() ; i++){
mapName.add(array.getJSONObject(i).getString("name"));
mapIds.add(array.getJSONObject(i).getString("id"));}
for(int i = 0 ; i < mapIds.size() ; i++)
if(mapIds.get(i).equals(mapId))
System.out.println("The most recent game was on "+mapName.get(i));
}
else
System.out.println("NULL");
}
catch (Exception e)
{
System.out.println("Caught exception");
System.out.println(e.getMessage());
}
}
In the output I get JSONObject["name"] not a string.
check JSON source. It seems like it may have no " around name value, or name is an object.
as example something like:
...
"name":John Doe,
...
or
"name":{"first":"John", "last":"Doe"},
...
BTW: Second is more expected. First must fail before, because it is wrong JSON. Value with no " around must be a number. But maybe name is empty like:
...
"name":,
...

How to get JSON Key/Value pairs with JSP [duplicate]

I'm very new to RESTFull WCF Services and even newer to calling them from an Android app. Here's my WCF service:
[ServiceContract]
public interface IPeople
{
[OperationContract]
void DoWork();
[WebGet(UriTemplate = "/GetPeople",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
[OperationContract]
string GetPeople();
}
The implementation of the interface:
public string GetPeople()
{
PeoplesEntities qe = new PeoplesEntities();
var result = from q in qe.tPeople
select q;
int count = result.Count();
int index = new Random().Next(count);
tPeople people = result.OrderBy(a=>a.ID).Skip(index).FirstOrDefault();
// result.First().ToString();
return people.FirstName + " - " + people.LastName;
}
and this is how i'm consuming it through an android service:
try {
HttpGet request = new HttpGet(SERVICE_URI + "/GetPeople");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONArray plates = new JSONArray(new String(buffer));
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
The exception I get is what is mentioned in the subject. What's strange is the value tha ti'm expecting is returned in the exception. I have no clue why it's expecting the square bracket.
FYI, most of the code i used is taken directly from online examples. Any help would be greatly appreciated. Thanks.
You're trying to create a JSONArray from a string that doesn't contain valid JSON array syntax. A JSONArray can be created from a string of the form [item1, item2, item3....] but you're just returning a single item in your string: FirstName LastName.
The line after it just returns the buffer, so the JSONArray call is pointless, anyway. You don't need the JSONArray call at all, since you're not dealing with JSON data. Just remove that line.

how to get a json array from php and use its value in android?

i am trying to get the data from database through a php file and then i want to use that data in android.i have tried a lot but it show me this error:type org.json.JSONObject cannot be converted to JSONArray.
followin is my php file and android code.also json array which was return is valid.
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$res = mysqli_query($con,$sql) or die('i cant');
//$result = array();
$abc="";
while($row = mysqli_fetch_assoc($res)){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
$final = array("result"=>$abc);
//echo json_encode(array("result"=>$result));
echo json_encode($final);
mysqli_close($con);
?>
andoid code
public void searchProfession() {
//testin work
String[] stringArray = new String[5];
//
try {
HttpParams httpParams = new BasicHttpParams();
HttpParams p = new BasicHttpParams();
p.setParameter("profession", SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
// return JSON String
if (inputStream != null) inputStream.close();
//ffffffffffffffffffffffffffff
//
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(result);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//testin work
String[] myarray;
//till here
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString(i);
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0], Toast.LENGTH_SHORT).show();
mylist.add(map);
}
} 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();
}
}
My Json : [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id‌​":"76","crtloc_lat":"34.769642","crtloc_lng":"72.361160"},{"user_id":"87","crtloc‌​_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.6971‌​17","crtloc_lng":"72.976631"}]
now i want to get the data in result array and show that data in android.for example i want to use all the(user_id) from that array
I think you got this error because jArray.getJSONObject(0); when i = 0 it's an array not an Object
your Json [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},...]
So jArray.getJSONObject(0); is [] not an object {"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}
You can check out this post on how to execute GET/POST/MULTIPART POST requests in android and then use that post to see how to parse your JSON data into pojo(s).
Hope that helps.
The error:type org.json.JSONObject cannot be converted to JSONArray is thrown when you try to fetch a JSONObject in the place of an array. An exception will also be thrown if you try to fetch empty objects so please check your code for empties.
start by
$abc="";
while($row = mysqli_fetch_assoc($res)){
if(!empty($row['user_id'])&&!empty($row['crtloc_lat'])&&!empty($row['crtloc_lng'])){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
}
Then
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString("crtloc_lat");//Use a key here
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0],Toast.LENGTH_SHORT).show();
mylist.add(map);
}

Can't properly parse JSON

I am having some issues while parsing JSON response in Android. The response I get is:
{
"response": "{\"session_token\":\"48500d8e42acc09aa45cb8f3a7ba2b30\",\"user_login\":\"newoff2\",\"user_id\":\"62\",\"user_profile_img\":\"http://onepgr.com/system/photos/62/medium/userfile054c35e29.png?1422089771\",\"success\":\"0\",\"user_email\":\"newoff2#pdmoffice.com\"}"
}
I need the values for user_login, success, user_profile_img, user_email. Here is what I tried so far, but it won't do what I need:
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
Log.d("Final Response",json);
jsonObject = new JSONObject(json);
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
Log.e("Parsed data is",str);
use this
json=json.replace("\\\"", "\"");
Log.e("resule",json);
try {
JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use regex to make your string JSON parsable
var res = data.replace(/\\"/g, '').replace(/\"{/g, '{').replace(/\}"/g, '}');
var jsonData = JSON.parse(res);
alert(jsonData.response.user_login);
Here is FIDDLE
Note: in fiddle I have declared your JSON with a ' ' to make it complete string
Use Scanner to remove \:
String resultStr = new Scanner(json).useDelimiter("\\A").next();
jsonObject = new JSONObject(resultStr);
Above is used for BufferedInputStream to get JSON string.
[UPDATE:]
For BufferReader, need to use StringBuilder to get JSON string:
StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
//for your JSON string, should use 'JSONTokener' to parse
jsonObject = (JSONObject) new JSONTokener(strBuilder.toString()).nextValue();
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
This should work for your case!
Try this....
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Result",result);
JSONObject jsonObject = new JSONObject(result);
String resJson=jsonObject.getString("response");
Log.d("Result",resJson);
JSONObject jsparam=new JSONObject(resJson);
String success=jsparam.getString("success");
Log.d("Value for success",success);
// JSONObject json1=jsonObject.getJSONObject("response");
//String objResponse = json1.getString("success");
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Categories