how to directly parse jsondata using JSONObject in java? [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
how to directly parse JSONdata using JSONObject in java as my JSON Data don't have any JSONArray .
JSONData:-
{{
"id": 481,
"date": "2016-12-30T13:56:10",
"date_gmt": "2016-12-30T13:56:10",
"guid": {
"rendered": "http://www.mytrendin.com/wp-content/uploads/2016/12/read- 1710011_1280.jpg"
},
"modified": "2016-12-30T13:56:20",
"modified_gmt": "2016-12-30T13:56:20",
"slug": "read-1710011_1280",
"type": "attachment",
"link": "http://www.mytrendin.com/increase-child-development/read-1710011_1280/",
"title": {
"rendered": "child development"
}}
java code
jsonObject = new JSONObject(results);
for(i=0;i<jsonObject.length();i++){
jsonObject=jsonObject.getJSONObject();
j = jsonObject.getString("type");
// mainActivityModel.setId();
}

You json is incorrect.
{
"id": 481,
"date": "2016-12-30T13:56:10",
"date_gmt": "2016-12-30T13:56:10",
"guid": { "rendered": "http://www.mytrendin.com/wp-content/uploads/2016/12/read- 1710011_1280.jpg" },
"modified": "2016-12-30T13:56:20", "modified_gmt": "2016-12-30T13:56:20",
"slug": "read-1710011_1280",
"type": "attachment",
"link": "http://www.mytrendin.com/increase-child-development/read-1710011_1280/", "title": { "rendered": "child development" }
}
You can parse json by this.
JSONObject obj = new JSONObject(result);
JSONObject guid=obj.getJSONObject("guid");
To get json object you will call getJSONObject() and to get String you will call getString()
And if you need to parse a json Array
JSONArray json_arr = new JSONArray(results);
for(i=0;i<json_arr.length();i++){
JSONObject jsonObject=json_arr.getJSONObject(i);
}

go through this tutorial it can help you in understanding json parsing
http://www.technotalkative.com/android-json-parsing/

Related

Parsing JSON response using Java [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
How to parse this json response using Java
{
"Name": {
"name_description": "NIL",
"date": "NIL"
},
"Age": {},
"City": {},
"SOAP": [
["content", "subtopic", "topic", "code"],
["I advised her to call 911, which he did.", "history of present illness", "subjective", "{}"]
]
}
You'd have to use an external library like json-simple
Read more about it here
Use a library called org.json, it is honestly the best java json library.
for example:
import org.json.JSONObject;
private static void createJSON(boolean prettyPrint) {
JSONObject tomJsonObj = new JSONObject();
tomJsonObj.put("name", "Tom");
tomJsonObj.put("birthday", "1940-02-10");
tomJsonObj.put("age", 76);
tomJsonObj.put("married", false);
// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);
tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);
if (prettyPrint) {
// With four indent spaces
System.out.println(tomJsonObj.toString(4));
} else {
System.out.println(tomJsonObj.toString());
}
}

How do i traverse this json data in java? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Hi i want to traverse this json data using android fast networking library but i am not able to do so. Can someone please suggest a way to be able to fetch id and filename of all the objects in the array?
Note -It has to be done using ANDROID FAST NETWORKING LIBRARY -https://github.com/amitshekhariitbhu/Fast-Android-Networking
[
{
"_id": "598ae8773376673353ef6da6",
"filename": "nldcjjzpesyhkkx1502275703450.jpg",
"votes": 33,
"__v": 0
},
{
"_id": "598ae83b3376673353ef6da5",
"filename": "xlwkfcxicwhqibw1502275643486.jpg",
"votes": 31,
"__v": 0
},
{
"_id": "598a2e7000c6717c3c04e534",
"filename": "ndkiqptbifqmnjz1502228078447.jpg",
"votes": 19,
"__v": 0
},
{
"_id": "5989ece9673738c027377710",
"filename": "seicmgkzubzavfy1502211303478.jpg",
"votes": 13,
"__v": 0
}
]
You can use GSON lib or you can retrieve using for loop like this:
try {
JSONArray jsonArray = new JSONArray(yourResponseStrOrJson);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("ID", jsonObject.getString("_id"));
//TOTO retrive other element
}
}catch (JSONException e){
e.printStackTrace();
}

How to get string values in to json and fetch message value from below request [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
{
"Header": {
"AppId": "appiddfdsf324",
"RecId": "fdsfrecid79878_879898_8797",
"SecureRefId": "fsdf5679567fsd_6789678",
"Type": "Other",
"Ver": "9.0.0",
"StartTS": "2016-09-26:07:48.798798-04:00"
},
"Application": {
"APP_OS": "Windows",
"APP_Runtime": ".Net67986",
"APP_AppName": "MPS",
"APP_AppVersion": "9.0.0.0",
"Host": "fsdhajkfh657895fsdajf",
"Channel": "N/A",
"APP_ReqId": "2f3d7987987-78987-987987-897-da"
},
"Service": {
"Key": "modification process",
"CallType": "HGDL",
"Operation": "processrequest",
"Port": "n/a"
},
"Results": {
"Elapsed": 0,
"Message": "Message Succesfully Deleted",
"TraceLevel": "Information"
},
"Security": {
"Vendor": "abfsdf"
},
"Extended_Fields": {
"CustomerId": "4564987987",
"MessageId": "768789fsdafasdf987987987fasdf",
"TimeElapsed": "1272.8171"
}
}
in above string value we are capturing from website result values we will get in a string format by using selenium webdriver.
This i need to convert and read value of "Message"
Note : i have tried below code
JsonElement jelement = new JsonParser().parse((String) elementText);
JsonObject jobject = jelement.getAsJsonObject();
jobject.getAsJsonObject("Results");
This above will provide complete result value of Result json but i required to fetch values which is present with "Message"
Below first line creates the JSONObject by passing String [which is of JSON format and it should be in JSON format, otherwise it will through an exception]
In Second line , as you have a JSON Object now, you can fetch any element from that,
e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type,
we can access any element by using . and depending on what are you fetching use get
e.g getString -> for getting String,
getInt->for getting Integer,
JSONObject-> for getting an JSONObject
getJSONArray-> for getting a JSONArray
JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object

how to get the value of lat and lng from the json

I have a json response.I want to get the value of lat and lng from the json response.But i didn't get the values.Please Help me.Below is my response.
{
"html_attributions": [],
"results": [
{
"geometry": {
"location": {
"lat": 9.493837,
"lng": 76.338506
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "2730a3d7ab068d666e61a02ce6160b4cd21a38c7",
"name": "Nagarjuna",
"place_id": "ChIJr0-U4vSECDsRtiALUlgZOzI",
"reference": "CmRcAAAA4yl72_x5llqvdshRJwuuntunXrYu33qdP5G7-I0CdHzcDsyd6wwqjxdNeqvT6vtRIoDoIk_WGNd62SYSoNEdBrpDrOcf5g5eZMj_vobhmF11mrujsQ_Yc7p-oGxQH0XtEhDNJdjQf_WlK_dRAckBzlA3GhQ_wzXs5RxoaxWDSEurm_R5syuovg",
"scope": "GOOGLE",
"types": [
"hospital",
"establishment"
],
"vicinity": "State Highway 40, Kodiveedu, Alappuzha"
},
{
"geometry": {
"location": {
"lat": 9.500542,
"lng": 76.341017
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "d5b6c81a53a346dea1263de7a777703bc72b8796",
"name": "SYDNEY OPTICALS",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 422,
"html_attributions": [],
"photo_reference": "CnRnAAAA_jg-NlSrVKkDOP7wXhPhvFTD8NW4A4aDI_Ptl3F9c_qt9QwdztNTG9Cr51uGIphpEUMyhsTfhhaa-TlfoL8MUEffbguZJ1AhKUwzfe7Mbrvm2KW8Y1EQXVw_3FglxA4LM1hqWJCK_AV4xcvOw1vuHRIQ8_keBYr29H8jK145RQ_PkRoUgPZ0qzcSNdIntc2ZI4WvBIR-TBQ",
"width": 630
}
],
"place_id": "ChIJl9tvIV6ECDsR7Cmf3KkIl-4",
"reference": "CnRjAAAA3qhFUcb8P9akE8xw-KwfF6OU6qvy2cVX4Sg0qK_xCOfeUEyxoFgwof8rk-Z2BBJ7Z4m7ZTbfdp78wqFbeLfojQWPldq7XDfzX0pLScBSysebEp9P4XmrsAO5qyqSUveb5jWcJDkYiOLKgaKMzoWQphIQbldrdJ9iEDHkGiQ7tleNYxoUnjcjcynUDMftaErRUQbOn-GkWj0",
"scope": "GOOGLE",
"types": [
"store",
"hospital",
"health",
"establishment"
],
"vicinity": "Mullakkal, Alappuzha"
}
],
"status": "OK"
}
This is the google api response i used for getting the list of hospitals.Anybode plese help me.Thanks in advance.
Use these steps:
Create a model class for that Json Response
Use Gson to parse the response
Then create an object of the class
using the object get the data variable from the class
I hope I can help.
First, validate your JSON with http://jsonlint.com/
Second, use this site to generate POJO: http://www.jsonschema2pojo.org/
make sure that Annotation GSON and Source type JSON are clicked ON!
Copy your classes in to your project.
Third: use GSON in Android :) (Retrofit is good for this)
Supposing you use the json.org Implementation for Java:
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject jo = new JSONObject(response);
JSONObject result = jo.getJSONArray("results").getJSONObject(0);
JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
try this
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject objResponce = new JSONObject(response);
JSONArray arrayResults=new JSONArray(objResponce.getString("results"));
if(arrayResults.length()>0)
{
for(int i=0;i<arrayResults.length();i++)
{
//--- get each json object from array -----
JSONObject objArrayResults = arrayResults.getJSONObject(i);
//--- get geometry json object from each object of array -----
JSONObject objGeometry=new JSONObject(objArrayResults.getString("geometry"));
//--- get location json object from geometry json object -----
JSONObject objLocation=new JSONObject(objGeometry.getString("location"));
System.out.println("Latitude :"+objLocation.getString("lat"));
System.out.println("Longitude :"+objLocation.getString("lng"));
}
}

Converting a specific JSON to java object format? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 9 years ago.
Iam new to java script and JSON, please help me in solving my problem. Below is the structure of my JSON in JavaScript
{
"name": "sample",
"def": [
{
"setId": 1,
"setDef": [
{
"name": "ABC",
"type": "STRING"
},
{
"name": "XYZ",
"type": "STRING"
}
]
},
{
"setId": 2,
"setDef": [
{
"name": "abc",
"type": "STRING"
},
{
"name": "xyz",
"type": "STRING"
}
]
}
]
}
in the backend, what should be the synatx of java method to receive this data
public void getJsonData(****){
}
How to parse this JSON data in java and what should be the syntax of method parameter ?
update 1: Edited the json format to make it valid
First create a class that will map your json object and give a name something like "DataObject". Then use the gson library and do the following:
String s = "";
DataObject obj = gson.fromJson(s, DataObject.class);
Your JSON is invalid, but assuming you fix that then you are looking for a library in Java which will serialize an annotated Java class to JSON, or deserialize JSON data to an annotated Java class.
There is a whole list of suitable libraries here:
http://json.org/java/

Categories