Parsing JSON from url in Java - 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);
}

Related

Parse these Json data with arrays in Android

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

Reading JSON file and Writing into a JSON file in Java using selenium Webdriver

I am working on an Automation Framework and I am looking for an alternative for excel to store test data, element locators and page objects.
So one my friend working on Automation is using json file to store all data as its easy and faster in reading and writing data, Also it can be easy in maintaining. They are using ruby as the language.
So I wanted to know if we can do the same using java & selenium to achieve this?
I have searched google for this and it looks like there is a library called "gson" from google, but none that shows how to use it using selenium.
please share your thoughts on this.
Thank you!!
I can't speak to including element locators in a JSON file, as I follow the page object model and include all those in the java classes. However, reading test data from a JSON file is very easy. It's been a while since I've messed around with this, but I used JSON Simple (which I still use to generate JSON objects/files) and did something like this to read in the file:
protected JSONObject getDataFile(String dataFileName) {
String dataFilePath = "src/test/resources/";
JSONObject testObject = null;
try {
FileReader reader = new FileReader(dataFilePath + dataFileName);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
testObject = (JSONObject) jsonObject;
} catch (Exception ex) {
ex.printStackTrace();
}
return testObject;
}
Once you have the JSON Object, JSON simple provides a few different ways to interact with it and get the values. I've played around with Gson a while back and I think that was fairly similar.
I don't know how your data file is/will be structured, but I had a key string that represented a test case name, and the value was a json object that contained other key-value pairs with the actual data and I fed that data to a TestNG data provider. If that is similar to your setup, I can share that code.
EDIT: Here is the method used by the #DataProvider
public Object[][] getTestScenarios(String dataFileName, String testCaseName) {
JSONArray testCase = (JSONArray) getDataFile(dataFileName).get(testCaseName);
List<JSONObject> testScenarioArray = new ArrayList<JSONObject>();
for (int i = 0; i < testCase.size(); i++) {
testScenarioArray.add((JSONObject) testCase.get(i));
}
Object[][] dataProviderArray = new Object[testScenarioArray.size()][];
for (int scenario = 0; scenario < testScenarioArray.size(); scenario++) {
String scenarioName = null;
if ((String) testScenarioArray.get(scenario).get("scenario") != null) {
scenarioName = (String) testScenarioArray.get(scenario).get("scenario");
} else {
scenarioName = "No scenario name specified";
};
dataProviderArray[scenario] = new Object[] { scenarioName, (JSONObject) testScenarioArray.get(scenario) };
}
return dataProviderArray;
}
The scenario name stuff could be removed, as I believe I only used that for logging or reporting, if I recall correctly. The reason I had it as a JSONArray and coded in this fashion is so a single test case could have an array with multiple scenarios with differing data. Didn't want the tests to have to care how many scenarios there were.
I have read a JSON Array from DB and made a list of a JSON object from JSON Array.
The array looks as follows:
[{
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO",
},
}, {
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO123",
}
}]
It is collected from DB in STRING form but is an array as it has SQUARE BRACKETS: [{Json1}, {Json2}].
String data = "ArrayFromDB";
JSONArray jsonArr = new JSONArray(data);
List<String> listJSON = new ArrayList<String>();
for (int i = 0; i < jsonArr.length(); i++)
{
listSMSJSON.add(jsonArr.getJSONObject(i).getJSONObject("sum").getString("message"));
}
System.out.println(listJSON);
listJSON is printed as [HELLO, HELLO123]

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

How to decode in java a json representation of Google appengine Text

I have two appengine applications and am serving a string representation of a JSONObject from one and picking it up in the other. Every thing works well if I don't include a Text object in the JSON
Here is the specific part of the JSON object causing the trouble:
,\"text\":\u003cText: rthBlog 1\r\n\"If you don\u0027t learn from history you are doomed to repeat i...\u003e,
Here is how it looks like in string form:
< Text: rthBlog 1
"If you don't learn from history you are doomed to repeat i...>
Here are the relevant code placing the string in the data store [I am using json.simple]:
Text item_text = new Text("default text"); //it get filled by text longer than 500 char's
JSONObject j = new JSONObject();
j.put("text", item_text);
j.put("item_links", j_links);
item.setProperty("as_json", j.toJSONString());
datastore.put(item);
Here is the code retrieving it wrapping it in a JSONArray the array in a JSONobject and producing a String [I am using appengine json]:
JSONArray search_results = new JSONArray();
for(Entity e: items)
{
String j = (String) e.getProperty("as_json");
JSONObject jo;
if(j != null)
{
System.out.println(TAG + ".searchItems() string as json: " + j);
jo = new JSONObject();
jo.put("item", j);
search_results.add(jo);
}
}
JSONObject jo = new JSONObject();
jo.put("items", search_results);
return jo.toJSONString();
Here is the code picking it up [I am using appengine json]:
try
{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = (JSONArray) jsonObject.get("items");
JSONObject array_member = null;
JSONObject j;
for(int i=0; i<jsonArray.length(); i++)
{
array_member = jsonArray.getJSONObject(i);
System.out.println("array member" + array_member);
/*Text text = (Text)array_member.get("text"); //
System.out.println(text.getValue());*/
String s_item = array_member.getString("item");
System.out.println("item in string form: " + s_item);
j = new JSONObject(s_item); //This is the exception causing line
You need to be in control of your serialization and deserialization to and from JSON ...
meaning complex object are represented as simple text or numbers.
Here you are trying to serialize a complex object which is not what it is intended for. Make sure you serialize only the value the object is holding not the entire object.
A nice and very powerfull library enabling to fully take control of the serialization/deserialization process is Jackson.

Server Response (JSON Format) to Array Conversion

I am working on an android app in which i send an http response to a server and get a response in string which is in JSON format, now on the basis of this response i need to generate a stacked column chart using AChartEngine for different equipments. The response string looks like as follows
[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":0,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":null,"EquipmentStatusDescription":null,"EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":0,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":null,"EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":561.60722222222023,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":"#008000","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":1,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.InCycle","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":134.57583333333525,"EquipmentDescription":"MTConnect","EquipmentId":5,"EquipmentName":"MTC 1","EquipmentStatusColor":"#FFFF00","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":"","EquipmentStatusTypeId":2,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.UnknownDowntime","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0}],"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":0,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":null,"EquipmentStatusDescription":null,"EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":0,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":null,"EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":[{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":495.61333333332925,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":"#008000","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":null,"EquipmentStatusTypeId":1,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeName.InCycle","EquipmentTimeZoneId":null,"EventData":null,"GeneralStatusState":0,"IsFirstRowData":false,"Percentage":0,"ReportGroupId":0,"ReportGroupName":null,"ReportGroupValue":null,"StatusAction":0,"StatusDuration":null,"TimeStamp":{"DateTime":"\/Date(-62135596800000)\/","OffsetMinutes":0},"UnknownDowntime_Duration":0,"UnknownDowntime_Percent":0},{"ChartDate":null,"CycleStatus":null,"Cycle_Duration":0,"Cycle_Percent":0,"Duration":200.56972222222623,"EquipmentDescription":null,"EquipmentId":1,"EquipmentName":"PCS Loop 1","EquipmentStatusColor":"#FFFF00","EquipmentStatusDescription":"In Cycle","EquipmentStatusId":0,"EquipmentStatusIdentifier":"","EquipmentStatusTypeId":2,"EquipmentStatusTypeName":null,"EquipmentStatusTypeName_resourceKey":"EquipmentStatusTypeNam
Now this is a response for five different equipments and how can i use this JSON string to an array so that i can extract the data of each equipment and send it to AChartEngine for drawing of chart?
You can convert the response string to JSONObject. The response you posted is JSONArray.
JSONArray jsonArray = new JSONArray(responseString);
int size = jsonArray.length();
ArrayList<JSONObject> arrayList = new ArrayList<JSONObject>();
for(int i= 0; i< size; i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
// use this jsonObject to get the value by passing the keys.
String value = jsonObject.optString(key);
//here is your array list of jsonobjects
arrayList.add(jsonObject);
}
Use below Code for Pass JsonArray and store Value into ArrayList.
JSONArray jArray = new JSONArray(mRes);
ArrayList<String> array1 = new ArrayList<String>();
for(int i= 0; i< size; i++) {
JSONObject jObject = jArray.getJSONObject(i);
String mValue = jObject.getString("your_json_object_name");
array1.add(mValue);
}
Use Gson api, it allows you to direct mapping of json objects to java objects. check following links for further reference:
http://code.google.com/p/google-gson/
https://sites.google.com/site/gson/gson-user-guide

Categories

Resources