JSONParser showing error in android app - java

i m trying to make app that can communicate with mysql (localhost)
Only problem is Eclipse is showing JSONParser Error
After trying to find solution for error i found this Tutorial jackson library tho http://jackson.codehaus.org/
i could not found any solution after 2 days digging into android code
JSONParser jParser = new JSONParser();
ERROR: Multiple markers at this line
- JSONParser cannot be resolved
to a type
- JSONParser cannot be resolved
to a type
and this line of code has same error showing
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Please help me so i can continue my app
help will highly appreciate!
thanks

If you need to parse a JSON string, you do not need to use any JSONParser class. The JSONObject itself can be used for parsing JSON.
Pass the JSON string to a new JSON object as following:
JSONObject responseObject = new JSONObject(response); //response is the JSON string that you get as response
String name = responseObject.get("name");
Similarly you can get the values directly from the responseObject itself. No need to use any third party libraries. You can find a very good documentation here.
EDIT:
I prefer Android Asynchronous Http Client for making web requests.

Related

Can I post JSON format in AWS Lambda function?

I have a JSON file and I want to send it to the RequestHandler. The error response is the following:
java.util.LinkedHashMap cannot be cast to java.lang.String
You're attempting to send a LinkedHashMap, as the error and #Mark B says, to the RequestHandler. Instead, "stringify" it into a JSON string first.
I recommend one of two libraries for this.
Google's GSON library
String jsonString = new Gson().toJson(jsonData, LinkedHashMap.class);
Java's JSON library
String jsonString = new JSONObject(jsonData).toString()
Then, send this string to the RequestHandler. Hope this helps.

getJSONObject error: JSONObject["..."] is not a JSONObject

I'm trying to parse a JSON string, but getting an error when trying to get a nested object:
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject);
System.out.println(jsonObject.keySet());
System.out.println(jsonObject.getJSONObject("matches"));
Below is the output in console. As far as I can see, the JSON is valid as jsonObject is created without an error. But when I try to obtain "matches" it throws an error. I've compared my code with tutorials but I can't see what the issue out to be:
{"matches":[{"id":233028,"awayTeam":{...
[matches, count, filters, competition]
Error in client: JSONObject["matches"] is not a JSONObject.
Anything I'm doing wrong? Happy to provide any further info if needed.
matches is an array, not an object. Use getJSONArray:
System.out.println(jsonObject.getJSONArray("matches"));
(Or more usefully:
System.out.println(Arrays.deepToString(jsonObject.getJSONArray("matches")));
since System.out.println on an array doesn't really show useful information on its own.)

Android Converting XML to Json Error passing through webservice

I want to sync my SQLite database on android device with SQL Server Data. I am using Webservice developed in Visual Studio.
The Webservice is returning XML which I am getting from
client.get("http://10.0.2.2/WebApi/api/mpapi/GetAllWriting", params, new AsyncHttpResponseHandler() {
Now I am passing the response to extract JSON array from it.
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
I am getting the following error.
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONArray.toString()
The value in response is
[{"Id":1,"Title":"Danish","Des":"Khan"},{"Id":2,"Title":"Rayan","Des":"Linkon"}]
What is the error is the XML not formatted properly? DO I need to change the Webservice./ Please guide as I have mostly copied the coding from multiple locations.
From your question it doesn't seems that you are getting xml data from your web service, however if in case you are sure that the response is xml you can try this Download java-json.jar. Add it into your library folder and get json object by executing the following code.
JSONObject jsonObj = null;
jsonObj = XML.toJSONObject(yourXmlObject);
You will need to import org.json.JSONObject; org.json.JSONException; org.json.XML; in order to execute above code.

Looking for a less verbose way to parse JSON in Android (Java)

I'm writing an app that uses JSON (from a Kimonolabs API) and while I was able to utilize my API effortlessly in Python as such:
results = json.loads(urllib.request.urlopen(KimonoAPIlink).read().decode('utf-8'))
Which returns a useable JSON dictionary:
title = results['results']['suart'][0]['stitle']['text']
href = results['results']['suart'][0]['stitle']['href']
In Java (Android specifically) I have to do it this way (Using Gson):
URL url = new URL(KimonoAPIlink);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonElement x = rootobj.getAsJsonObject("results").getAsJsonArray("suart").get(0);
JsonObject y = x.getAsJsonObject();
title.setText(y.getAsJsonObject("stitle").getAsJsonPrimitive("text").toString().replace("\"", "").replace("\\","\""));
Is there any way to do this that isn't so verbose and complicated? (my code works, I'd just like it to be more simple and clean)
Moreover, can I somehow parse the whole nested JSON object into something useful (like python does) and not reparse it each layer I access?
Thanks in advance.
Edit: I've also seen people use Apache commons.io on here for this, but I don't think it returns a different JSON object (i.e. I'd still have to parse every layer)
Check out GSON, Jackson or Moshi
What you are looking for is lookup using JsonPath, wherein JSON coordinates are represented by a string with syntax pretty similar to the one you are using in Python (as well as other featuress).
For example, in your case it would be $.results.suart[o].stitle.text.
A quick look in the docs and the gson github shows it is not implemented in gson, although the JsonReader class does support a method to return that value.
There is a library implementation JsonPath in java (called JsonPath). Here's a one line code for your case (ignoring connection detail):
String result = JsonPath.parse("[some json]").read("$.results.suart[o].stitle.text");

Parsing RSS Feed with JSON and Populating a List Android App

Im brand new to Android Application development and I am working on an application that will get an RSS feed from a specific url that returns JSON data , what I am wondering is what is the best way to translate this from JSON to populate the list ,
I was thinking of making objects to hold the individual posts and then create a list of them from the json but is this the best way it seems a little rough
Just looking for idea on how others perform this action
May also be helpful to other beginners as no concrete reference base is around for this subject.
thanks chris
Very basic example:
String resultString = "{"name":"Fred Nurke", "age":"56"}";
JSONObject jobj = new JSONObject(resultString); /*This converts the string
into members of the JSON Object which
you can then manipulate*/
Log.d(jobj.getString("name")+ " is " + jobj.getString("age") + " years old");
As I said that is a very basic example of working with JSON in Android. What you'll probably be dealing with is not just a JSONObject, but a JSONArray, which as the name implies is a special Array class of JSONObjects.
Working with a JSONArray can be done as follows: (Assume we've filled the resultString already)
JSONArray jsonArr = new JSONArray(resultString);
JSONObject jsonobj;
for(int i = 0; i < jsonArr.length(); i++){
jsonobj = JSONArray.getJSONObject(i);
}
Once you have your JSONObject you can start working with it in the same manner as above.
Hope that helps.
The android API has built in support for handling JSON data which is helpful for parsing. It uses the classes shown here:
http://www.json.org/java/
API reference from android here: http://developer.android.com/reference/org/json/JSONObject.html
At a high level, You can create a JSONObject by simply passing the entire JSON string into its constructor. From there it offers a list of get methods to pull primitive types, strings, or nested JSON objects out.
If you want to keep the posts saved, I would still parse the JSON data into an object for storage, otherwise you could just create a list from the data returned directly from the JSON objects.

Categories