Android : Json Parsing show error - java

[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?

Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")

String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.

Related

how to remove json object from json Array using org.json.simple

I have a JSON file which is an JSON ARRAY with some JSON Objects and I want to remove the entire json Object if the value of longitude or latitude is an empty string "".
I am using the library org.json.simple. Here is my json file:
[ { "Longitude": 9.96233,
"Latitude": 49.80404 },
{
"Longitude": 6.11499,
"Latitude": 50.76891
},
{ "Longitude": 6.80592,
"Latitude": 51.53548
},
{
"Longitude": 9.50523,
"Latitude": 51.31991 },
{
"Longitude": ""
"Latitude": ""
},
{
"Longitude": 9.93368,
"Latitude": ""
},
{
"Longitude": 11.56122,
"Latitude": 48.14496
},
{
"Longitude": 13.34253,
"Latitude": 52.5319
},
{
"Longitude": 6.11327,
"Latitude": 50.77715
},
{
"Longitude": ""
"Latitude": ""
}
]
and here's where I am stuck. :
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader ("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node -> {
String vari = (String)((JSONObject)node).get("longitude").toString();
if (vari==null) {
((JSONObject) node).remove();
System.out.println("deleted");
}
}
...
Any suggestions how can I change my code ?
You need to remove the node from the list but because of concurrent modification problem (modifying the list you are looping) you need another list.
I think it is easiest to collect into the new list all the nodes that qualify so like:
#SuppressWarnings("unchecked")
#Test
public void test() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray listNonNull = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>)list).forEach(node -> {
// here any check that qualifies the node like also checking "Latitude"
// Also no need to cast to a String
Object vari = node.get("Longitude");
if (vari != null && !vari.equals("")) {
listNonNull.add(node);
}
});
} catch (Exception e) {
throw e;
}
}
If you wish to use only the original list you can collect items to be removed to an another list and use it to remove nodes from the original list:
public void test2() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray toBeRemoved = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>) list).forEach(node -> {
Object vari = node.get("Longitude");
// here any check that qualifies the node like also checking "Latitude"
if (vari != null && !vari.equals("")) {
return; // not to be removed
}
toBeRemoved.add(node);
});
list.removeAll(toBeRemoved);
} catch (Exception e) {
throw e;
}
}
use .remove instead of .clear in the code.
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
ArrayList<JSONObject> objList = (ArrayList<JSONObject>) list.stream().filter(node -> {
String longitude = ((JSONObject) node).get("Longitude").toString();
String latitude = ((JSONObject) node).get("Latitude").toString();
if (longitude.isEmpty() || latitude.isEmpty()) {
return false;
}
return true;
}).collect(Collectors.toList());
} catch (IOException | ParseException e) {
e.printStackTrace();
}

How to create a JSONObject for nested json

I am unable to create a json object for nested json.
I can create json objects for basic json.
I am unable to add further fields.
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
} catch (JSONException e) {
e.printStackTrace();
}
Here is my json:
{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}
You just need to create a new JSONObject then append it to the parent object with its new name. An example is shown below appending the ballot:
JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one
System.out.println(jsonObject.toString());
Output(with some formatting):
{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}
You can also use JSONArray instead and append it in the same manner.
Try this:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
it's not all the fields but it's all the different types hope it helps.
Output:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}

How to read JSON file with Arrays and Objects in Java

I'm trying to read a file which is fetched from Opentdb and access data from only specific keys.
I've tried all of the given methods which includes GSON and Json Simple but ended up having errors.
Here's my JSON:
{
"response_code": 0,
"results": [
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which of the following sports is not part of the triathlon?",
"correct_answer": "Horse-Riding",
"incorrect_answers": [
"Cycling",
"Swimming",
"Running"
]
},
{
"category": "Sports",
"type": "multiple",
"difficulty": "easy",
"question": "Which English football club has the nickname \u0026#039;The Foxes\u0026#039;?",
"correct_answer": "Leicester City",
"incorrect_answers": [
"Northampton Town",
"Bradford City",
"West Bromwich Albion"
]
},
I want to access only category, difficulty, question , correct_answer and incorrect_answers .
excample for you
try {
URL resource = App.class.getClassLoader().getResource("info.json");
System.out.println(resource.toString());
FileReader reader = new FileReader(resource.getFile());
// Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray infoList = (JSONArray) obj;
System.out.println(infoList);
Information i = new Information();
List<Information> info = i.parseInformationObject(infoList);
saveInformation(info);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
and
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}

Parsing Multiple Objects from a Single JSON File using JAVA

I have the following json file from which I am trying to extract data and store it to a database.
*//FirstBlockStart*
{
"_id": {
"$oid": "572395d8b1bf87f39645b94e"
},
"ReferenceDate": {
"$date": 1461949267500
},
"Url": "http://goTechhy.com",
"PublicationDate": {
"$date": 1461553200000
},
"LastUpdateDate": {
"$date": 1461553200000
},
}
//FirstBlockEnd
//SecondBlockStart
{
"_id": {
"$oid": "572394d8b1bf87f39645b94e"
},
"ReferenceDate": {
"$date": 1461969267500
},
"Url": "http://goTechhy.com",
"PublicationDate": {
"$date": 1461553200000
},
"LastUpdateDate": {
"$date": 1461353200000
},
}
//SecondBlockEnd
I need to extract the Oid, ReferenceData, PublicationData, LastUpdateDate from the JSON
Here is what I have tried.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONObject Obj = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("E:\\Json2Db\\PlayStore1.json")));
//JSONObject Obj = (JSONObject) parser.parse(new FileReader("E:\\Json2Db\\PlayStore1.json"));
getAppID(Obj);
System.out.println(getAppID(Obj));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private static String getAppID(JSONObject obj) {
JSONObject appIDObj = (JSONObject) obj.get("_id");
String appID = (String) appIDObj.get("$oid");
return appID;
}
When I try to execute this code, I get the following error.
Unexpected token LEFT BRACE({) at position 4644.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:146)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at com.freelancer.kaja.JsonParse.main(JsonParse.java:18)
But at the same time, When there is only One Block (say FirstBlock) in JSON, it works fine.. I am new to this JSON thing.. I dont know what I am missing here.. Please give your suggestions.
I would like the output to be something like this.
oid: 572395d8b1bf87f39645b94e
ReferenceDate:1461949267500
Url:http://goTechhy.com
PublicationDate:1461553200000
LastUpdateDate: 1461553200000
oid: 572395d8b1bf87f39645b94e
ReferenceDate:1461949267500
Url:http://goTechhy.com
PublicationDate:1461553200000
LastUpdateDate: 1461553200000

How to parse login response in android?

I am confused about parsing so I want to know about how to parse. Whenever I login with valid login id and password give response
{
"data": {
"status": "1",
"Full Name": [
{
"user_id": 1,
"user_name": "deepika#soms.in",
"full_name": "",
"display_name": "",
"token": "",
"photo_url": "http://clients.vfactor.in/putt2gether/images/profile/default.jpg"
}
],
"Event": [
{
"latest_event_id": "",
"format_id": ""
}
],
"msg": "Success Login"
}
}
and if invalid login id then give response
{
"Error": {
"msg": "Please Enter valid Email Address"
}
try {
JSONObject obj = new JSONObject(response);
if (obj.has("Error")) {
JSONObject objError = obj.getJSONObject("Error");
} else if (obj.has("data")) {
JSONObject objData = obj.getJSONObject("data");
}
} catch (Exception e) {
e.printStackTrace();
}
You need to parse the json answer.
There are many sources to learn how to do that:
Oracle documentation
Jackson documentation - Jackson is a library to parse json
GSon documentation - Another json parser
Let's assume response be,
String response;
try
{
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data"))
{
JSONObject jsonObjData = jsonObject.getJSONObject("data");
String status = jsonObject.getString("status");
JSONArray jsonArrayName = jsonObjData.getJSONArray("Full Name");
for (int i = 0; i < jsonArrayName.length(); i++) {
JSONObject jsonObj = jsonArrayName.getJSONObject(i);
Integer user_id = jsonObj.getInt("user_id");
String user_name = jsonObj.getString("user_name");
String full_name = jsonObj.getString("full_name");
String display_name = jsonObj.getString("display_name");
String photo_url = jsonObj.getString("photo_url");
}
JSONArray jsonArrayEvent = jsonObjData.getJSONArray("Event");
for (int i = 0; i < jsonArrayEvent.length(); i++) {
JSONObject jsonObj = jsonArrayEvent.getJSONObject(i);
String latest_event_id = jsonObj.getString("latest_event_id");
String format_id = jsonObj.getString("format_id");
}
String msg = jsonObject.getString("msg");
} else if (jsonObject.has("Error")) {
JSONObject jsonObjError = jsonObject.getJSONObject("Error");
String msg = jsonObjError.getString("msg");
}
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources