I'm trying to build the following JSON Request Body.
It's my first time with JSON and I'm following this examples, but still struggling.
I've been taking a look to GSON but wanted to manage pure JSON first, and maybe for something so small it's not worth it to add GSON library?
Could you help me with the code?
Thanks.
{
locations:
[
{
latLng:
{
lat: 40.900799,
lng: 8.606102
}
},
{
latLng:
{
lat: 42.900799,
lng: 9.606102
}
}
]
}
EDIT:
Here is the Web Service I am trying to consume and here a request sample.
Use json objects.
Do something like that.
Don't write json by hand, you could easily do a mistake.
public JSON() throws JSONException
{
JSONArray locArr=new JSONArray();
locArr.put(createLatLng(40.900799, 8.606102));
locArr.put(createLatLng(42.900799, 9.606102));
JSONObject main=new JSONObject();
main.put("locations", locArr);
Log.d("JSON",main.toString());
}
public JSONObject createLatLng(double lat, double lng) throws JSONException
{
JSONObject latLng=new JSONObject();
latLng.put("lat",lat);
latLng.put("lon",lng);
JSONObject latLngWrap=new JSONObject();
latLngWrap.put("latLng",latLng);
return latLngWrap;
}
JSON notation requires the "" around field names. Values should only be wrapped, if they are string.
{
"locations":
[
{
"latLng":
{
"lat": 40.900799,
"lng": 8.606102
}
},
{
"latLng":
{
"lat": 42.900799,
"lng": 9.606102
}
}
]
}
You can always verify, if you JSON is correct using
http://jsonlint.com/
Expanding on maciekczwa's answer. JSON (unlike arguably XML) isn't really meant to be looked at with human eyes. It very quickly becomes very hard to see where one object starts and ends and what's wrapping what. Use his example to create your main JSON object and then fill it with whatever objects you need to. When you're all done you can convert it to string for transport very easily, without having to look at it, and doing it this way means not having to worry about what labels need to be wrapped in what kinds of quotes etc.
And eskalera is 100% correct. JSON requires all fields to be wrapped in quotes (the rules around whether or not they can be single quotes or *MUST be double quotes vary from implementation to implementation, but again, this is only relevant if you're constructing the JSON manually, as you should only do in instances where it's EXTREMELY simple (and even then... probably not).
Related
I am trying to figure out how to parse data that comes from Zoho CRM API inside of Android Studio. I am relatively new, but I do know how to parse data from a JSON response like this:
{
"Data": [
{ "subdata": "data"
}
]
}
Something kind of like that I can parse no problem in Android Studio, even with multiple subdata points, it's not that hard. But, I am at a complete loss when it comes to parsing data that looks like this:
{"response":{"result":{"Contacts":{"row":[{"no":"1","FL":
[{"content":"1822766000000272057","val":"CONTACTID"},
{"content":"Lisa","val":"First Name"}]},{"no":"2","FL":
[{"content":"1822766000000119148","val":"CONTACTID"},
{"content":"Eric","val":"First
Name"}]}]}},"uri":"/crm/private/json/Contacts/searchRecords"}}
Does anyone know how to parse data like this inside of Android Studio?
Update: I have a photo of what the JSON looks like in Json Viewer:
Just take it layer by layer. It can get a little verbose so I like to have a class called JSONUtils or something and use convenience methods like this to help parsing JSON without having to wrap everything in try-catch blocks:
/**
* Retrieves a json object from the passed in json object.
* #param json The json object from which the returned json object will be retrieved.
* #param key The key whose value is the json object to be returned.
* #return A json object.
* */
public static JSONObject jsonObjectFromJSONForKey(JSONObject json, String key) {
try {
return json.getJSONObject(key);
}
catch (JSONException e) {
return null;
}
}
You can make variations of this for any other data types, and by doing so you can just have your try-catch blocks in one area, and just check for null when invoking these kind of methods.
JSONObject responseJSON = JSONUtils.jsonObjectFromJSONForKey(json, "response");
if (responseJSON != null) {
JSONObject resultJSON = JSONUtils.jsonObjectFromJSONForKey(responseJSON, "result");
// So on and so forth...
}
When user login to the app I am getting JSON response with username, pasword, token, userID and onboarding. As per the requirement of the application I hava to redirect the user to home page if this onboarding value is "true" in the JSON data.
[
{
"display_name": "my email ID",
"msg_status": "success",
"userid": "userID",
"plan_type": "none",
"token": "my token",
"requires_onboarding": true
}
]
I get all these fields in my java code. Now I want to let user go to the home screen if this onboarding value is true.
Please help.
If you get this json as a String, parse it like the following code. IF you are already with a JSONArray, then you won't need to use the first line.
JSONArray jsonArray = new JSONArray(jsonString);
JSONObject json2 = jsonArray.get(0);
boolean onBoarding = json2.getBoolean("requires_onboarding");
Then you can do whatever you want with your boolean variable.
If you have questions about JSON, here's a little information about it:
JSONArray is something like: events:[ {"object1": value}, {"object1":Value} ]
Which means that you get the JSONArray and use jsonArray.get(position) for each thing inside it. (Note that you can have JSONArrays inside JSONArrays.
JSONObject is basically the "string" name with a value attached.
So you'll always have to see how the data you're getting is structured to parse right and choose correctly between JSONObjects or Arrays.
Here is a complete explanation the difference.
Simplest way to do this:
boolean what = false;
try{
JSONArray mRootArray = new JSONArray(jsonString);
JSONObject jInnerObject = mRootArray.getJSONObject(0);
what = jInnerObject.getBoolean("requires_onboarding");
}catch(Exception e){
what = false;
e.printstacktrace();
}
Now maintain as per state of boolean:
if(what){
// Go to netxt screen
}else{
// Stay here
}
Hope this will help you,
I got the required output guys thank you for your response it is as I mentioned below.
String name = list.get(5);
if (name.equals("true"))
startActivity(new Intent(Login.this, OnBoardingOne.class));
How to get latitude and longitude object. please help
{
"category":[
{
"name":"Judging_Point",
"title":"",
"iconimg":"33.png",
"count":0,
"content":""
},
{
"name":"Street_Trading_Stalls",
"title":"Street Trading Stalls",
"iconimg":"34.png",
"count":0,
"content":""
},
{
"name":"static_sound_systems",
"title":"Sound Systems",
"count":29,
"iconimg":"24.png",
"content":[
{
"latitude":"51.52603767293402",
"longitude":" -0.2136941301305184",
"title":"4 Play",
},
{
"latitude":"51.52603767293402",
"longitude":" -0.2136941301305184",
"title":"4 Play",
},
One option would be to use JSONSimple with is a Java JSON lib. Android may contain a json lib allready but i like json simple because its simple:)
Just create a Parser object and read the String.
Then create a JSONObject by getting the "category" and so on
#user3796430 Try integrating GSON library. It will definitely help you...
I have a Groovy/Grails website that is being used to send data to Android clients via JSON. I have created both the Android client and the Groovy/Grails website; and they can output the same objects in JSON.
I can successfully create the respective objects in Android by mapping the JSON output to Java objects, however I was wondering if it's possible to use the JSON output to create a new domain object in Groovy/Grails? Is there a way of passing the JSON output to a controller action so that object will be created?
Here is an example of the JSON that I'd like to send;
{
"class":"org.icc.callrz.BusinessCard.BusinessCard",
"id":1,
"businessCardDesigns":[],
"emailAddrs":[
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":1,
"address":"chris#krslynx.com",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":0,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"H"
}
},
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":2,
"address":"cb#i-cc.cc",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":1,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"W"
}
}
]
}
The "class" matches to the Domain I'd like to save to, the ID is the ID of the Domain, then each item within the businessCardDesigns and emailAddrs needs to be saved using similar methods (in the Domain the businessCardDesigns and emailAddrs are ArrayLists). Many thanks in advance!
SOLUTION:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json) {
Owner.fromJsonToOwner(json).persist();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
Using the built-in Grails JSON converter makes this easier than the other answers, in my opinion:
import grails.converters.JSON
class PersonController {
def save = {
def person = new Person(JSON.parse(params.person))
person.save(flush:true)
}
}
The other benefits are:
There's no need to muck around in any config files
The resulting JSON object can be manipulated, if necessary, before assigning properties
It's far clearer in the code what's happening (we're parsing a JSON object and setting the properties on the Person entity)
I know you already accepted an answer but if I'm reading your question right, there's a built in "Grails" way to do this.
Create an entry for your action in URLMappings.groovy and turn on request parsing. For example, I create RESTful mappings like so:
"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
action = [POST: "save"]
}
And then in you controller
def save = {
def businessCardInstance = new BusinessCard(params.businessCard)
....
businessCardInstance.save(flush:true)
}
this might work for you
http://static.springsource.org/spring-roo/reference/html/base-json.html
{
"serviceType":"IMAGE_ANDROID",
"parameters":[
[
{
"itemId":"it003376",
"itemNameInEng":"8th Chennai International Film Festival Photos",
"itemSmallImage":"http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg",
"count":"110"
},
{
"itemId":"it003375",
"itemNameInEng":"Actress Aishwarya Rai Special Photos",
"itemSmallImage":"http://122.183.217.134:8080/sivajitv/photos/20101215230917.jpg",
"count":"7"
},
{
"itemId":"it003374",
"itemNameInEng":"Actor Srikanth Flag off The Avon Greenathon Bicycle Rally ",
"itemSmallImage":"http://122.183.217.134:8080/sivajitv/photos/20101215212620.jpg",
"count":"43"
},
{
"itemId":"it003373",
"itemNameInEng":"Kadamai Kanniyam Kattupadu Movie Launch Photos",
"itemSmallImage":"http://122.183.217.134:8080/sivajitv/photos/20101213001908.jpg",
"count":"32"
},
{
"itemId":"it003372",
"itemNameInEng":"Kanden Audio Launch Photos",
"itemSmallImage":"http://122.183.217.134:8080/sivajitv/photos/20101210044334.jpg",
"count":"126"
}
]
]
}
this is my response
i want to parse the parameters from this response and i need to parse all data in parameter
please provide me correct solution
Make use of JSONArray class in org.json.JSONArray..
see this link
Accessing members of items in a JSONArray with Java
Use the org.json classes in the SDK.