iOS5: Unable to read value from JSON using NSJSONSerialization - java

I am trying to parse JSON data. The data is an Array with objects inside it.
This is the JSON array I get from the URL:
["{content:Airfare}",
"{content:Dues \/ Subscriptions}",
"{content:Education \/ Training}",
"{content:Entertainment}",
"{content:GS-OCWD}",
"{content:GS-OCWE}",
"{content:GS-Shift A}",
"{content:GS-Shift B}",
"{content:GS-Shift C}",
"{content:Ground Transportation}",
"{content:Legal Fees}",
"{content:Lodging}",
"{content:Meals}",
"{content:Mileage}",
"{content:Office Supplies}",
"{content:Other Expenses}",
"{content:Prof. Dues & Memberships}",
"{content:Rental Car}",
"{content:Telephone}",
"{content:Telephone \/ Internet}",
"{content:Tolls \/ Parking}"]
This is the code for parsing the JSON array in my .m file
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:8080/de.vogella.jersey.final/rest/notes"]];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &error];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#",error);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", [item objectForKey:#"content"]);
[_identificationTypes1 addObject:item];
}
}
When the line NSLog(#"Item: %#", [item objectForKey:#"content"]); is executed the app crashes and gives a [__NSCFString objectForKey:]: unrecognized selector error. It is unable to read the key content. If I change the line to NSLog(#"Item: %#", item); I can see all the values like {content:Airfare}. I just need the Airfare value. Can someone help me
This is the code to generate the JSON. I am using Jersey and JAVA.
Can you help me with the JSON format from the URL? This is my DAO code:
public JSONArray getAllNotes()
{
PreparedStatement prepStmt = null;
List<Note> notes = new ArrayList<Note>();
try {
String cSQL = "SELECT EXPENDITURE_TYPE FROM PA_ONLINE_EXPENDITURE_TYPES_V;
prepStmt = connection.prepareStatement(cSQL);
ResultSet result = prepStmt.executeQuery();
while (result.next())
{
Note note = new Note();
//note.setNoteId(result.getInt(1));
note.setContent(result.getString(1));
//note.setCreatedDate( new java.util.Date(result.getDate(3).getTime()));
notes.add(note);
}
return new JSONArray(notes);
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
This is the POJO method:
#Override
public String toString() {
//return "{Content:"+content+"}" ;
return "ExpType [content=" + content + "]";
}
This is the method that calls the DAO method:
#GET
#Produces({MediaType.APPLICATION_JSON})
public JSONArray getNotes() {
return dao.getAllNotes();
}

Your JSON is wrong. It's just an array of strings and that's why you're getting this error. What it really should be like is:
[{"content":"Airfare"},
{"content":"Dues \/ Subscriptions"},
{"content":"Education \/ Training"},
... etc]

Related

Get ID of the room from Json

I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}

Gson parser crashes due to blank character

I have a file in JSON format. Gson parser crashes when it encounters a blank in it, as in State = "West Virginia", but it can parse "West-Virginia" where the blank character is replaced. I am using BufferedReader in Java.
But if I pass the same string hard-coded, the parser works.
import java.io.* ;
import com.google.gson.*;
public class gson_test {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
BufferedReader br2 = null ;
String jsonStr = "[{month = august, weather:clear}, [333] , {addr : {place = {city = city_name, county : its_name}, state = \"West Virginia\" } } ]" ;
// System.out.printf("json-str : %s \n", jsonStr);
GsonParseStr(jsonStr, (JsonElement) null );
try {
String file2read_json = "c:\\enter\\filename\\here";
br2 = new BufferedReader(new FileReader(file2read_json));
// https://sites.google.com/site/gson/gson-user-guide#TOC-Array-Examples
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
Object obj2 = gson.fromJson(br2, Object.class); // parses json-str into an object
GsonParseStr(obj2.toString(), (JsonElement) null );
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br2 != null) {
br2.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static void GsonParseStr(String jsonStr, JsonElement elem) {
JsonParser parser2 = new JsonParser();
elem = parser2.parse(jsonStr); // this stmt crashes for the blank char
System.out.printf("parse str : %s \n", jsonStr);
}
}
My file's content is:
[{month = august, weather:clear}, [333] , {addr : {place = {city = city_name, county : its_name}, state = "West.Virginia" } } ]
If I change "West.Virginia" to "West Virginia" the program crashes.
The file should get parsed the same way as 'file-contents in the form of raw string'.
PS : As suggested by JPinzon, I need quotes around (West Virginia) in the file, which I did have. But they have to be further escaped. Thus : (State: "West Virginia") won't do; it should be (State: "\"West Virginia\""). Optionally, the key 'State' can have double-quotes around it, but that is optional.
Try fixing your JSON to this:
[{"month":"august", "weather":"clear"}, [333], {"addr":{"place":{"city":"city_name", "county":"its_name"}, "state":"West Virginia"}}]
... or nicely formatted:
[
{
"month":"august",
"weather":"clear"
},
[
333
],
{
"addr":{
"place":{
"city":"city_name",
"county":"its_name"
},
"state":"West Virginia"
}
}
]
If you debug, you will see that the string obj2.toString() doesn't contain quotes around "West Virginia" because the gson.fromJson(br2, Object.class) has removed them while parsing. That's why it crashes.
To avoid this error you can try adding escaped quotes in your file like this state = "\"West Virginia\""

Java GSON check data

I'm having trouble with gson:
For example I have this output from website:
[["connected"], ["user1":"Hello"], ["user2":"Hey"], ["disconnected"]]
But I want parse this JSON and output something like this:
connected
user1 says: Hello
user2 says: Hey
disconnected
I quicly wrote this code:
public static void PrintEvents(String id){
String response = Post.getResponse(Server()+"events?id="+id,"");
// response is [["connected"],["user1":"Hello"],["user2":"Hey"],["disconnected"]]
JsonElement parse = (new JsonParser()).parse(response); //found this in internet
int bound = ????????????; // Should be 4
for (int i=1;i<=bound;i++){
String data = ???????????;
if (data == "connected" || data == "disconnected") then {
System.out.println(data);
}else if(?????==2){// to check how many strings there is, if it's ["abc","def"] or ["abc"]
String data2 = ??????????????;
System.out.println(data+" says: "+data2);
}else{
//something else
}
};
}
What should I insert to these parts with question marks to make code work?
I cannot find any way to make it work...
Sorry for my bad English.
EDIT: Changed response to [["connected"], ["user1","Hello"], ["user2","Hey"], ["disconnected"]]. Earlier response was not valid JSON.
The response that you have pasted is not a valid json. paste it in http://www.jsoneditoronline.org/ and see the error.
Please find the below code snippet:
public static void printEvents(String id)
{
String response = "[[\"connected\"] ,[\"user1:Hello\"],[\"user2:Hey\"],[\"disconnected\"]]";
JsonElement parse = (new JsonParser()).parse(response); //found this in internet
int bound = ((JsonArray)parse).size(); // Should be 4
for (int i = 0; i < bound; i++) {
String data = ((JsonArray)parse).get(0).getAsString();
if (data.equals("connected") || data.equals("disconnected")) {
System.out.println(data);
continue;
}
String[] splittedData = data.split(":");
if (splittedData.length
== 2) {// to check how many strings there is, if it's ["abc","def"] or ["abc"]
System.out.println(splittedData[0] + " says: " + splittedData[1]);
}
/*
*else{
* your else logic goes here
* }
* */
}
}
Couple of suggestions:
If you are new to json world, use jackson instead of Gson.
the response is not a good design. Slightly correct json:
{
"firstKey": "connected",
"userResponses": [
{
"user1": "hey"
},
{
"user2": "hi"
}
],
"lastKey": "disconnected"
}
Also try to define pojos , instead of working inline with json.
You need to define a separate class like this:
class MyClass{
String name;
String value;
}
and then:
List<MyClass> myclasses = new Gson().fromJson(response, new TypeToken<List<MyClass>>(){}.getType());
then
for(MyClass myclass: myclasses){
...
}

Setting Parameters through url javaplay

so as part of some work I've been doing I was given a file with WebServices that are being used in a Swift application. I have zero familiarity with WebServices and only know Java through syntax understanding. I need to call one of these gets with a parameter from the swift application. What I'm trying to figure out first and foremost is how I can call one of these webservices with a parameter from the URL it's associated with. For example down below I want to call the method
http://localhost:9000/ListVehicleByPlateNumber
and I want to specify the parameter through the URL say something like
http://localhost:9000/ListVehicleByPlateNumber?para="123"
But this doesn't assign any value to the parameter and I'm not getting results. If I hardcode so that the string used in the function is = "123" it gives me the results I'm looking for. I just need to know how I can pass this parameter through the url, syntax-wise.
Routes file
GET /ListVehicleByPlateNumber controllers.NewVehicle.listVehicleByPlateNumber(para: String ?="")
Controller
public Result listVehicleByPlateNumber(String para){
NewVehicleModel v = new NewVehicleModel();
List<NewVehicleModel> vehiclesC = v.searchByPlateVehicle(para);
ObjectNode wrapper = Json.newObject();
ObjectNode msg = Json.newObject();
if(vehiclesC != null) {
msg.set("VehicleList", toJson(vehiclesC));
wrapper.set("success", msg);
return ok(wrapper);
}else{
msg.put("error", "There are no vehicles with the plate number");
wrapper.set("error", msg);
return badRequest(wrapper);
}
}
Where it's called
public List<NewVehicleModel> searchByPlateVehicle(String plateNumber){
Transaction t = Ebean.beginTransaction();
List<NewVehicleModel> vehicles = new ArrayList<>();
try {
String sql = "SELECT V.idNewVehicle, V.VehicleType,V.PlateNumber,V.VehicleJurisdiction,V.State,V.Vin,V.Year, " +
"V.Make,V.modelos,V.RegistrationNumber,V.InsuranceCompany,V.PurchaseDate,V.ExpirationDate,V.idPersonaFK " +
"FROM NewVehicle V " +
"WHERE V.PlateNumber = :plateNumber";
RawSql rawSql = RawSqlBuilder.parse(sql)
.columnMapping("V.idNewVehicle", "idNewVehicle")
.columnMapping("V.State", "state")
.columnMapping("V.VehicleType", "vehicleType")
.columnMapping("V.PlateNumber", "plateNumber")
.columnMapping("V.VehicleJurisdiction", "vehicleJurisdiction")
.columnMapping("V.Vin", "vin")
.columnMapping("V.Year", "year")
.columnMapping("V.Make", "make")
.columnMapping("V.modelos", "modelos")
.columnMapping("V.RegistrationNumber", "registrationNumber")
.columnMapping("V.InsuranceCompany", "insuranceCompany")
.columnMapping("V.PurchaseDate", "purchaseDate")
.columnMapping("V.ExpirationDate", "expirationDate")
.columnMapping("V.idPersonaFK", "idPersonaFK")
.create();
Query<NewVehicleModel> query = Ebean.find(NewVehicleModel.class);
query.setRawSql(rawSql)
.setParameter("plateNumber", plateNumber);
vehicles = query.findList();
t.commit();
}
catch (Exception e){
System.out.println(e.getMessage());
}finally {
t.end();
}
return vehicles;
}
Found my own answer. I ended up casting from Integer to String here's how it looks in routes
GET /ListVehicleByPlateNumber/:para controllers.NewVehicle.listVehicleByPlateNumber(para: Integer )
Controller
public Result listVehicleByPlateNumber(int para){
String p = String.valueOf(para);
URI Format for value 123 example.
http://localhost:9000/ListVehicleByPlateNumber/123

getJSONObject and subsequent getString returns null

This is a very straightforward question, but this error is very mysterious to me as I have not been able to find a solution or anyone else who has had this problem. I've also used a very similar technique in another activity and it worked just fine. I am making an android application which makes a POST request to a server. The response is a JSONObject that must be parsed into a number and another JSONObject which must also be parsed, and its values assigned to an array of CurrentGame objects. The first call to getJSONObject works fine, but calling getString on that JSONObject returns the following error:
java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.xxxxx.xxxxx.CurrentGame.oppEmail' on a null object reference
Here is my java code:
private void handleResponse(JSONObject response){
int numGroups = 0;
try{
numGroups = response.getInt("Number");
}catch(JSONException e){
e.printStackTrace();
}
Log.i("Number of Groups", String.valueOf(numGroups));
CurrentGame[] currentGames = new CurrentGame[numGroups];
JSONObject current;
int yourTurn = 0;
for(int i = 0; i < numGroups; i++){
try{
current = response.getJSONObject(String.valueOf(i));
Log.i("Current JSONObject: ", String.valueOf(current));
if(current.has("OppEmail")){
currentGames[i].oppEmail = current.getString("OppEmail");
}
if(current.has("OppName")) {
currentGames[i].oppName = current.getString("OppName");
}
if(current.has("Group")) {
currentGames[i].group = current.getString("Group");
}
if(current.has("YourTurn")) {
yourTurn = current.getInt("YourTurn");
}
if(yourTurn == 0){
currentGames[i].yourTurn = true;
}
else{
currentGames[i].yourTurn = false;
}
}
catch (JSONException e){
e.printStackTrace();
}
}
}
Shouldn't the JSONObject.has() check at least be preventing this error?
I know the first getInt() and getJSONObject are working. Heres the Log:
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx D/Response:﹕ {"Number":2,"0":{"Group":"Test Group 1","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0},"1":{"Group":"Test Group 2","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":1}}
06-21 21:58:56.644 20116-20116/com.xxxxxx.xxxxxt I/Number of Groups﹕ 2
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx I/Current JSONObject﹕ {"Group":"Test Group 1","OppEmail":"xxxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0}
Here's the server code:
$games['Number'] = $numgames;
if($numgames > 0){
$i = 0;
while($row = mysqli_fetch_array($getgames)){
$currGame['Group'] = $row['GroupName'];
// Get the opponent's email and username
if($row['Player1'] != $email){
$opponent = $row['Player1'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
else if($row['Player2'] != $email){
$opponent = $row['Player2'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
// Determine if it is this player's turn
if($row['CurrentPlayer'] != $email){
$currGame['YourTurn'] = 0;
}
else{
$currGame['YourTurn'] = 1;
}
$games[$i] = $currGame;
$i++;
}
}
//Echo array of groups
header('Content-Type: application/json');
$response = json_encode($games);
echo $response;
Thank you in advance for any ideas as to what I'm doing wrong here. I know similar questions have been asked about getString() returning null, but having read them all I'm still very stumped.
Problem is caused by :
currentGames[i].oppEmail = current.getString("OppEmail");
line.
Because currentGames Array is initialized with size 2 but not added any item of type CurrentGame.
Instead of using currentGames[i].oppEmail create a object of CurrentGame class add all values then add it in currentGames Array like:
CurrentGame objCurrentGame=new CurrentGame();
if(current.has("OppEmail")){
objCurrentGame.oppEmail = current.getString("OppEmail");
}
... same for other fields
...
//Add objCurrentGame to Array
currentGames[i]=objCurrentGame;
Parsing json this way is not robust and error prone, it is recommended to use such libraries as
Gson
Jackson
Retrofit
as these open source libraries offer stable implementation for such purposes and there is no need to reinvent the wheel yourself.
example:
YourPojoClass obj = new Gson().fromJson("{SomeJsonString}", YourPojoClass.class);
In this way, you get the strongly typed pojo instance.You don't even need write the POJO class yourself, and there are many online service that can generate the POJO class out of json strings:
http://www.jsonschema2pojo.org/
http://pojo.sodhanalibrary.com/

Categories

Resources