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":,
...
Related
I am trying to transform a json file received through REST API into a list of java objects. Everything works well until couple runnings when I get StackOverFlow error.If I am not calling that method everything works well. I do not have any idea of how to solve this. Thank you
The error is :
Exception in thread "main" java.lang.StackOverflowError
at org.json.JSONTokener.nextClean(JSONTokener.java:292)
at org.json.JSONTokener.nextValue(JSONTokener.java:422)
at org.json.JSONObject.<init>(JSONObject.java:225)
at org.json.JSONTokener.nextValue(JSONTokener.java:431)
at org.json.JSONObject.<init>(JSONObject.java:244)
at org.json.JSONTokener.nextValue(JSONTokener.java:431)
at org.json.JSONArray.<init>(JSONArray.java:124)
at org.json.JSONTokener.nextValue(JSONTokener.java:434)
at org.json.JSONObject.<init>(JSONObject.java:244)
at org.json.JSONTokener.nextValue(JSONTokener.java:431)
at org.json.JSONObject.<init>(JSONObject.java:244)
at org.json.JSONTokener.nextValue(JSONTokener.java:431)
at org.json.JSONArray.<init>(JSONArray.java:124)
at org.json.JSONTokener.nextValue(JSONTokener.java:434)
at org.json.JSONObject.<init>(JSONObject.java:244)
The method that calls the REST Api is :
public List<Student> getAllStudents() {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/students/getAllStudents" +
"");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
ObjectMapper objMap = new ObjectMapper();
Student tabusca = new Student();
output = br.readLine();
tabusca = objMap.readValue(output, Student.class);
System.out.println(tabusca.toString());
String file = "";
while ((output = br.readLine()) != null) {
file += output;
//System.out.println(output);
}
//System.out.println(file);
JSONArray jsonArray= new JSONArray(file);
List<Student> list = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++) {
Student p = new Student();
p.setStudentId(jsonArray.getJSONObject(i).getLong("studentId"));
p.setEmail(jsonArray.getJSONObject(i).getString("email"));
p.setPassword(jsonArray.getJSONObject(i).getString("password"));
p.setFullname(jsonArray.getJSONObject(i).getString("fullname"));
p.setGrupa(jsonArray.getJSONObject(i).getLong("grupa"));
p.setHobby(jsonArray.getJSONObject(i).getString("hobby"));
p.setToken(jsonArray.getJSONObject(i).getString("token"));
p.setAssigmentStudent(null);
p.setAttendances(null);
p.setStudentUid(null);
list.add(p);
}
httpClient.getConnectionManager().shutdown();
return list;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The issue is your JSON is too 'deep'. There are too many nested elements in your json. The org.json parser gets too many recursive method calls to it resulting into Stackoverflow.
Even if you change your json library, you may still run in same problem.
To solve the issue you should either reconsider the JSON structure or increase the JRE stack size using jvm argument eg -Xss4m
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
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.
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.697117","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);
}
When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.