Parsing Multiple Objects from a Single JSON File using JAVA - 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

Related

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

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}

String to JSONObject in Android raise exception

Here is the JSON format in String object which i am trying to convert into JSONObject in android.
{
"city":[
{
"id":"1",
"name":"Mumbai"
},
{
"id":"2",
"name":"Delhi"
},
{
"id":"3",
"name":"Chennai"
},
{
"id":"4",
"name":"Kolkatta"
}
],
"locality":[
{
"id":"1",
"locality_city_id":"1",
"locality_name":"Andheri"
},
{
"id":"2",
"locality_city_id":"1",
"locality_name":"Bandra"
},
{
"id":"3",
"locality_city_id":"1",
"locality_name":"Dadar"
},
{
"id":"4",
"locality_city_id":"1",
"locality_name":"Thane"
}
],
"diseases":[
{
"id":"1",
"disease_name":"Blood Pressure"
},
{
"id":"2",
"disease_name":"Diebetes"
},
{
"id":"3",
"disease_name":"Hypertention"
},
{
"id":"4",
"disease_name":"Dyslexia"
}
]
}
I copied it to JSON beautifier and it says it is a valid JSON.
But this raises exception. Is there anything wrong in the JSON format ?
Code used is:
JSONObject jsonObject = new JSONObject(jsonString);
Exception stacktrace:
08-11 11:22:33.548: W/System.err(3055): org.json.JSONException: Value
{"city":[{"id":"1","name":"Mumbai"},{"id":"2","name":"Delhi"},{"id":"3","name":"Chennai"},{"id":"4","name":"Kolkatta"}],"locality":[{"id":"1","locality_city_id":"1","locality_name":"Andheri"},{"id":"2","locality_city_id":"1","locality_name":"Bandra"},{"id":"3","locality_city_id":"1","locality_name":"Dadar"},{"id":"4","locality_city_id":"1","locality_name":"Thane"}],"diseases":[{"id":"1","disease_name":"Blood
Pressure"},{"id":"2","disease_name":"Diebetes"},{"id":"3","disease_name":"Hypertention"},{"id":"4","disease_name":"Dyslexia"}]}
of type java.lang.String cannot be converted to JSONObject 08-11
11:22:33.548: W/System.err(3055): at
org.json.JSON.typeMismatch(JSON.java:111) 08-11 11:22:33.548:
W/System.err(3055): at
org.json.JSONObject.(JSONObject.java:158) 08-11 11:22:33.548:
W/System.err(3055): at
org.json.JSONObject.(JSONObject.java:171)
I've tried with your JSON and the following code snippet works for me.
String strJson = YOUR_JSON_STRING_HERE;
try {
JSONObject json = new JSONObject(strJson);
System.out.println(json);
} catch (JSONException e) {
e.printStackTrace();
}
Paste the whole code, because what ever you've provided works fine

how to create a json format in our own format in android?

i like to create a JSON format to send to service. i format of the json in mentioned below.
the product object is came from loop. please assume i=1 and give me a answer.
{
"tableid": 41,
"status": 141,
"products": [
{
"menuitemid": 349,
"qty": "1",
"taxids": [
{
"taxid": "1",
"Amount": 0.15
}
],
"taxamount": 0.15,
"seatname": "Seat 1",
"modifiers": [],
"saleid": "140704131457005701",
"discountshiftlevelid": ""
},
{
"menuitemid": 44,
"qty": "1",
"taxids": [
{
"taxid": "1",
"Amount": 0.13425
}
],
"taxamount": 0.13425,
"seatname": "Seat 1"
},
{
"menuitemid": 44,
"qty": "1",
"taxids": [
{
"taxid": "1",
"Amount": 0.13425
}
],
"taxamount": 0.13425,
"seatname": "Seat 2"
},
{
"menuitemid": 44,
"qty": "1",
"taxids": [
{
"taxid": "1",
"Amount": 0.13425
}
],
"taxamount": 0.13425,
"seatname": "Seat 2"
}
],
"checkdiscountshiftlevelid": "",
"customerid": "0"
}
i tried many times i didn't get the result. my sample code is below.
package servicecall;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Savecheckandprint {
public void calll() throws JSONException
{
JSONObject obj1 = new JSONObject();
try {
obj1.put("tableid", "41");
obj1.put("status", "141");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject products = new JSONObject();
try {
products.put("menuitemid", "349");
products.put("qty", "2");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
//jsonArray.put(obj1);
jsonArray.put(products);
JSONObject studentsObj = new JSONObject();
studentsObj.put("", obj1);
studentsObj.put("", jsonArray);
String jsonStr = studentsObj.toString();
System.out.println("jsonString: "+jsonStr);
}
}
am new to android. i don't know how to create a JSON structure like about. please help me. please help me.
Not sure i understand your question but you should look into using GSON which allows for easy JSON creation from Objects/classes
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
package servicecall;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Savecheckandprint {
public void calll() throws JSONException
{
JSONObject obj1 = new JSONObject();
try {
obj1.put("tableid", "41");
obj1.put("status", "141");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject products = new JSONObject();
try {
products.put("menuitemid", "349");
products.put("qty", "2");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(products);
try {
obj1.put("products", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = obj1.toString();
System.out.println("jsonString: "+jsonStr);
}
}

Android : Json Parsing show error

[
{
"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.

Categories

Resources