Parse these Json data with arrays in Android - java

please tell me I am new to use JSON data. Thanks in Advance.
https://api.myjson.com/bins/waw4y
how to parse this data in android. I am adding the two client details. In that
First, I have added an object for the whole content and after I have added the different client names and age, car with arrays. so please make it as easy.
Thanks in advance
JSON stands for JavaScript Object Notation. It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting
temperature only.

This code is not feasible with dynamic implementation of JSON, Just to showcase the Parsing proccess.
JSONObject client = null;
try {
client = new JSONObject(response);
JSONArray clientChild1 = client.getJSONArray("client1");
JSONArray clientChild2 = client.getJSONArray("client2");
for (int j = 0; j < clientChild1.length(); j++) {
JSONObject objectChild = clientChild1.getJSONObject(j);
Log.e("NAME", "onCreate: " + objectChild.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Unable to retrieve data from POST request

I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!
I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..
String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}
The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/

Getting simple Json string from url and converting it to String[] Android

I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"

Twitter hbc API: how to get the individual tweet texts?

I am going to use Twitter for some semantic text analysis in a school class. I downloaded the Hosebird Client for Java and is running the FilterStreamExample.java: https://github.com/twitter/hbc/blob/master/hbc-example/src/main/java/com/twitter/hbc/example/FilterStreamExample.java
Running it, I get a lot of data about the users' profiles, their settings, background images, etc. I just want the tweeted text only. And maybe the location and username.
It may be a stupid question, but how do I make it only display the "texts" information? Right now, it just prints out everything.
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
System.out.println(msg);
}
I could probably do a search for "text" in the strings themselves, but it seems a bit cumbersome. Isn't there any better way to do it?
The response from the twitter Streaming API is JSON String. Parse the string into JSON Object and get the value from the key "text"
import org.json.*;
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
JSONObject obj = new JSONObject(msg);
String text= obj.getString("text");
System.out.println(msg);
}
*Not Tested
Refer the following for parsing JSON in Java
How to parse JSON in Java

Parsing JSON from url in Java

(Prefacing this by saying that I am extremely new to JSON, aside from the last several hours I have spent trying to figure this out)
I am working on a personal android app that will search a URL that includes JSON data.
For example:
http://magictcgprices.appspot.com/api/images/imageurl.json?cardname=Pillar%20of%20Flame&cardset=fnmp
Provides the link to the card picture url.
Basically, it is a tool for Magic the Gathering so that I can search a card name and either have the picture shown to me, or bring the prices up with this URL:
http://magictcgprices.appspot.com/api/tcgplayer/price.json?cardname=Tarmogoyf&cardset=Modern%20Masters ----> Returns: ["$97.25", "$115.20", "$149.98"]
However, these JSON arrays do not have field names. I am stuck on how I will go about retrieving the JSON results from the webpage and relaying them back to java so I can manipulate them again. I have messed around with Jackson JSON libraries with no luck.
Try this..
JSONArray new_array = new JSONArray(response);
for(int i = 0; i < new_array.length; i++){
System.out.println("Values : "+new_array.getString(i));
}
This should help:
JSONArray yourData = new JSONArray(response);
int len = yourData.length();
String data;
for (int i = 0; i < len; i++) {
data = new String(yourData.get(i));
System.out.println(data);
}

JSON Parsing in Android [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I have searched alot on JSON Parsing in Android, but couldn't quite convinced. Actually got a brief idea but not so clear yet regarding JSON Parsing.
How to implement the JSON Parsing in the Application?
This is a very simple JSON String
{"key1":"value1","key2":"value2"}
In order to get values for it use JSONObject like this :
JSONObject json_obj=new JSONObject(your json string);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");
This is a slightly complex json string
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
In order to extract values from this use JSONArray
JSONArray jArray=new JSONArray(your json string);
for(int i=0;i<(jArray.length());i++)
{
JSONObject json_obj=jArray.getJSONObject(i);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");
}
Hope this helps a bit...........
You can also check out Google's GSON library here. The GSON user guide here has some useful examples to help get you started. I've found GSON to be simple and powerful.
See: http://developer.android.com/reference/org/json/package-summary.html
Primarily, you'll be working with JSONArray and JSONObject.
Simple example:
try {
JSONObject json = new JSONObject(jsonString);
int someInt = json.getInt("someInt");
String someString = json.getString("someString");
} catch (JSONException e) {
Log.d(TAG, "Failed to load from JSON: " + e.getMessage());
}
You can use the org.json package, bundled in the SDK.
See here: http://developer.android.com/reference/org/json/JSONTokener.html
One more choice: use Jackson.
Simple usage; if you have a POJO to bind to:
ObjectMapper mapper = new ObjectMapper(); // reusable
MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream
// back to JSON:
String jsonString = mapper.writeValue(value);
to a Map:
Map<?,?> map = mapper.readValue(source, Map.class);
or to a Tree: (similar to what default Android org.json package provides)
JsonNode treeRoot = mapper.readTree(source);
and more examples can be found at http://wiki.fasterxml.com/JacksonInFiveMinutes.
Benefits compared to other packages is that it is lightning fast; very flexible and versatile (POJOs, maps/lists, json trees, even streaming parser), and is actively developed.

Categories

Resources