I have a web servlet that returns a json which is stored in my bb mobile app as string in json format....
Now I want to parse the string to extract values from it...
using
JSONObject jsobject = new JSONObject(jsonString);
returns an error:
json must start with {
My JSON generated is in this format
[
{"LASTNAME":"akre","FIRSTNAME":"swapnil"},
{"LASTNAME":"akre","FIRSTNAME":"swapnil"},
{"LASTNAME":"akre","FIRSTNAME":"swapnil"}
]
which is corect format as verified by jsonlint.com....
yes, json must start with { and end with } , what you can do is you put your json array in
{}, so it will be parsed correctly. JsonLint parses the partial json as well thats why it is showing it as correct. You can try like following
yes, json must start with { and end with } , what you can do is you put your json array in {}, so it will be parsed correctly as jsonobject. JsonLint parses the partial json as well thats why it is showing it as correct
{
"data": [
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
},
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
},
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
}
]
}
I'm assuming you're using this library.
Your JSON is an Array, so you'll have to use the JSONArray class to parse it
Related
Hello I am beginner and trying to understand how to send an array with objects. Does the server understand what an array is like Int, Strings or Booleans? Do you have to send the array in a string for JSON? What I do not understand?
var productsResult = ""
let encoder = JSONEncoder()
let productObject = ProductUsed(name: "Custom name", reason: "This Reason", apply_way: "Intravenous infusion", dosing: "2x", date_start: "22-02-1999", date_end: "22-03-2003")
do {
let result = try encoder.encode([productObject])
if let resultString = String(data: result, encoding: .utf8) {
print(resultString)
productsResult = resultString
}
} catch {
print(error)
}
json["products_used"] = productsResult
And I sent to server with parameters like this:
parameters: ["pregnancy_week": 0, "body_height": 198, "initials": "John Appleseed", "heavy_effect": false, "sex": "Male", "pregnancy": false, "month_of_birth": 3, "reaction": "No option checked", "additional_info": "Eeee", "products_used": "[{\"date_end\":\"22-03-2003\",\"dosing\":\"2x\",\"date_start\":\"22-02-1999\",\"apply_way\":\"Intravenous infusion\",\"name\":\"Custom name\",\"reason\":\"This Reason\"}]", "description": "Eeee", "result": "Recovery without lasting consequences", "year_of_birth": 1983, "day_of_birth": 11, "issue_date": "15-11-2020", "body_weight": 78]
but printed "resultString" in log and looks good...
[{"date_end":"22-03-2003","dosing":"2x","date_start":"22-02-1999","apply_way":"Intravenous infusion","name":"Custom name","reason":"This Reason"}]
What's wrong in my code and why I have " \ " between words in "products_used" key?
JSON, unlike XML, does not specify the structure and type explicitly. This means that the server must know what JSON data to expect.
In JSON there are a few value types (https://www.w3schools.com/js/js_json_syntax.asp):
a string
a number
an array
a boolean
null
a JSON object (a dictionary with tags like { "first" : "John", "last" : "Doe" }). This allows nesting.
A JSON object is a set of tag-value pairs. The tag and value are separated by : and pairs are separated by ,.
An array is a list of JSON values. So for example [ "hello", world" ] is a JSON array with 2 strings and [ 12, 54 ] is a JSON array with two numbers.
Your parameter list ["pregnancy_week": 0, "body_height": 198, ... is not an array but a dictionary instead. A Swift dictionary is translated to an JSON object, not a JSON array.
The \ you see printed acts as escape character. This escape character is used to allow you to have a " inside the string.
That's just a few things that I hope will help understand things a bit better. Your questions are pretty basic, which is fine and it's great you want to understand things. But instead of us explaining everything here, I think it would be best if you'd read about the structure of JSON and how JSON works in Swift on your own.
I've been trying to retrieve the value of code for a while now. This is the json I'm getting back from the server:
{
"message": "The given data was invalid.",
"errors": {
"code": [
"The code has already been taken."
]
}
}
How do I get the value of "code" with swiftyJson?
I've already tried this but I don't think it's correct.
let list: Dictionary<String, JSON> = json["errors"].dictionaryValue
var retunValue = list.values.first
You can access the first element of the "code" array like this:
json["errors"]["code"].array?.first?.string
This will give you nil if code were an empty array, or the JSON isn't the expected structure.
Since "code" is an array, it might contain more than 1 string, so you might want a [String] instead:
json["errors"]["code"].array?.compactMap { $0.string } ?? []
This will give you an empty array if the JSON is not the expected structure.
I have following REST API response:
"items":
[
{
"empid": "1234",
"name": "Santosh",
"hiredby": "Mark",
"date": "2017-01-31,00:19:41 PST",
},
{
"empid": "5678",
"name": "Kumar",
"hiredby": "Bob",
"date": "2017-01-31,08:30:31 PST"
}
]
My query is : - How do i get empid based on querying name as Kumar.
For example: I need to find "Kumar" name and get his empid. (that is, search by name and get his empid as response) I'm able to get the response and store it in Response object. but, from response object how can i traverse and query to get the required value.
Also,
I tried by retrieving as:
String name = get(REST_ENDPOINT).then().body("items.name",hasItems("Kumar")).extract().path("items.empid").toString();
when i print the response i get collection of the empid like [1234,5678], where as my expectation is to get only 5678.
Do I need to parse via JSONArray and JSONObject and iterate the response?
Please suggest.
You can use something like this
response1.jsonPath().getList("collect { it.credentials.findAll { it.credentialType == 'Ban User Name'}.credentialId }.flatten()")
I am trying to serialize my object graph into JSON using the SwiftyJSON Library. I have a function in a BirthdayEvent class named "toJSON" which converts individual Birthday Events into swiftyJSON objects successfully.
However I am keen to have something like the following structure to the JSON:
"birthdays" : [
{
"eventId": "...",
"date": "01/01/2000",
...
},
{
"eventId": "...",
"date": "01/02/2001",
...
},
...
]
I am finding it difficult to create a JSON dictionary with the String "birthday" as the key and the array of BirthdayEvent JSON items as the value.
I have the following code:
var birthdaysJSON: JSON = JSON(self.events.map { $0.toJSON() })
var jsonOutput : JSON = ["birthdays": birthdaysJSON]
The first line successfully creates a JSON object of the array of events, but I cannot seem to use this in the dictionary literal. I get an error of "Value of type 'JSON' does not conform to expected dictionary value type 'AnyObject'.
Can you tell me where I am going wrong, or am I over-complicating this?
To create a JSON dictionary, you have to initialize the JSON object on jsonOutput just like you did with birthdaysJSON:
var jsonOutput: JSON = JSON(["birthdays": birthdaysJSON])
I'm new to Swift, my task is to get data from GET request and present its data on UI. Below is my code:
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, myUrl, headers: headers)
.responseJSON{ JSON in
if let jsonResult = JSON as? Array<Dictionary<String, String>> {
let title = jsonResult[0]["title"]
print(title)
}
}
I'm able to get data with request but I don't know how to parse JSON object in some format (probably json array) that can be later used to present in TableView. Please help
Data example:
[
{
"title": "Sony",
"content": "Tech content",
"image": "http://google.com/content/device.jpg?06"
},
{
"title": "Nexus",
"content": "Nexus 6 is a new beginning",
"image": "http://google.com/content/device.jpg?01"
} ]
JSON data can be represented in different forms. It can be encoded as a string or converted into known data types on the platform. The main components of json are arrays, associative arrays (or dictionaries), and values.
The swift struct you are displaying reads as follows.
It's an array. Array content displayed here starts and ends with [] like [1,2,3] would be an array of ints.
The data in the the array a list of dictionaries. dictionary start and ends with {} . like {"key":"value"}
Those dictionaries contain the keys "title","content" and "image".
because you requested responseJSON from alamo file you will be returned a parsed structure and all you need to do read it like you would normal arrays and dictionaries as that is what it is.
You should read this documentation on how to make safe code that uses the above logic.
http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial