How to parse JSON object without JSONdecoder in iOS? [duplicate] - json

This question already has an answer here:
Decode Dictionary with Random Initial Key
(1 answer)
Closed 1 year ago.
Okay, so I received this werid JSON format couple days back, I don't know if it is possible to decode it but I would like to learn if we could.
{
"status" : true,
"orderHistory": {
"5" : {
"productId" : 0,
"productName" : "Anchovy",
"quantity" : 1,
"price" : "199"
"variation": ""
},
"17" : {
"productId" : 0,
"productName" : "Anchovy",
"quantity" : 1,
"price" : "199"
"variation": ""
},
"98" : {
"productId" : 0,
"productName" : "Anchovy",
"quantity" : 1,
"price" : "199"
"variation": ""
}
}
}
Order History is supposed to be an Array, but in this case backend is sending these Objects with random string keys, Reason we can't create a Decodable Model is that the keys are random,
Any ideas on how to decode this data and use it into our iOS app?

It is best to continue using the JSON decoder.
The root model matching the JSON would look like this:
struct Body: Decodable {
let status: Bool
let orderHistory: [String: Order]
}
The Order Model will be simple.

Related

How to retrieve all key-value pairs avoiding key duplication from JSON in Groovy script

I am totally new to groovy script and would like some help to solve this out. I have a JSON response I want to manipulate and get desired parameters back by avoiding duplication. The Json response does not have indexes like 0,1,2.. that I can iterate through.
Here is the response that I want to work with:
{
"AuthenticateV2" : {
"displayName" : "Verification of authentication",
"description" : "notification ",
"smsTemplate" : "authentication.v2.0_sms",
"emailHeaderTemplate" : "v2.0_header",
"emailBodyTemplate" : "html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE"
},
"supportedPlans" : [
"connectGo"
]
},
"PasswordRecovery" : {
"displayName" : "Verification of password recovery",
"description" : "notification",
"smsTemplate" : "recovery.v1.0_sms",
"emailHeaderTemplate" : "recovery.v1.0_header",
"emailBodyTemplate" : "recovery.v1.0_body_html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE",
"adminInitiated" : false,
"authnId" : "AUTHENTICATION_IDENTIFIER",
"authnType" : "EMAIL",
"user" : {
"displayName" : "USER_DISPLAY_NAME"
}
},
"supportedPlans" : [
"connectGo"
]
},
"PasswordReset" : {
"displayName" : "password reset",
"description" : "notification",
"smsTemplate" : "recovery.v1.0_sms",
"emailHeaderTemplate" : "recovery.v1.0_header",
"emailBodyTemplate" : "html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"user" : {
"displayName" : "USER_DISPLAY_NAME"
}
}
The expected output that I want to have:
{
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE",
"customToken" : "VERIFICATION_CODE",
"adminInitiated" : false,
"authnId" : "AUTHENTICATION_IDENTIFIER",
"authnType" : "EMAIL"
}
I need to retrieve all fields under parameters tag and also want to avoid duplication
You should first get familiar with parsing and producing JSON in Groovy.
Then, assuming the provided response is a valid JSON (it's not - there are 2 closing curlies (}) missing at the end) to get all the parameters keys merged into one JSON we have to convert the JSON string into a Map object first using JsonSlurper:
def validJsonResponse = '<your valid JSON string>'
Map parsedResponse = new JsonSlurper().parseText(validJsonResponse) as Map
Now, when we have a parsedResponse map we can iterate over all the root items in the response and transform them into the desired form (which is all the unique parameters keys) using Map::collectEntries method:
Map uniqueParameters = parsedResponse.collectEntries { it.value['parameters'] }
Finally, we can convert the uniqueParameters result back into a pretty printed JSON string using JsonOuput:
println JsonOutput.prettyPrint(JsonOutput.toJson(uniqueParameters))
After applying all the above we'll get the output
{
"displayName": "USER_DISPLAY_NAME",
"actionTokenURL": "VERIFICATION_LINK",
"customToken": "VERIFICATION_CODE",
"adminInitiated": false,
"authnId": "AUTHENTICATION_IDENTIFIER",
"authnType": "EMAIL",
"user": {
"displayName": "USER_DISPLAY_NAME"
}
}
If you want to get rid of user entry from the final output just remove it from the resulting uniqueParameters map (uniqueParameters.remove('user')) before converting it back to JSON string.

My JSON parsing fails

Im using SwiftyJSON, Alamofire_SwiftyJSON and Alamofire libraries. I'm trying to parse my response but it returns nothing("definitions" fails to print).
JSON isn't empty it has got the response.
So, my code looks like the following (nothing fails, it all compiles)
Alamofire.request(request).responseSwiftyJSON { dataResponse in
if let JSON = dataResponse.result.value {
print(JSON)
if let definitions = JSON["results"]["lexicalEntries"]["entries"]["senses"]["definitions"].string {
print(definitions)
print("Hello")
}}
}
My response model looks like (this is not the whole response, that's just what I want to reach :
{
"results" : [
{
"language" : "en",
"id" : "ace",
"type" : "headword",
"lexicalEntries" : [
{
"language" : "en",
"entries" : [
{
"etymologies" : [
"Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
],
"grammaticalFeatures" : [
{
"type" : "Number",
"text" : "Singular"
}
],
"homographNumber" : "000",
"senses" : [
{
"definitions" : [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
I think that my problem is in, should I add any parentheses or any symbols?
if let definitions = JSON["results"]["lexicalEntries"]["entries"]["senses"]["definitions"].string
You are not indexing the corresponding arrays in your JSON response, to access the definitions array you can simply use
JSON['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions']

Query local JSON File in Swift [duplicate]

This question already has answers here:
Search through a large json file for a particular key value pair
(2 answers)
Closed 5 years ago.
I have a local JSON file that I am trying to parse based on a value. I can correctly get all the values from the file but what's the best solution to get a particular value. let say i have the following JSON data
[{ "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338,
"state" : "MA", "_id" : "01001" }
, { "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ],
"pop"
: 36963, "state" : "MA", "_id" : "01002" }
, { "city" : "BARRE", "loc" : [ -72.10835400000001, 42.409698 ], "pop"
: 4546, "state" : "MA", "_id" : "01005" }]
Say I only want to show line with _id = 01002. What would be the best solution to achieve what I am asking? I added what I already have, any help would be greatly appreciated.
if let file = Bundle.main.url(forResource: "zip", withExtension: "json") {
do {
let data = try Data(contentsOf: file)
let json = JSON(data: data)
let jsonRecord = json["_id"]
print("this is json \(jsonRecord)")
} catch {
// handle error
}
}
found my answer using different terminology
here
Swift array version:
let peopleNamedTom = arrayOfPeople.filter { $0["Name"] == "Tom" }
SwiftyJSON array version:
let peopleNamedTom = arrayOfPeople.filter { $1["Name"] == "Tom" }

Mongoose: Save a JSON with embedded documents, using schemas with references

everyone. I tried to save a JSON (RecordNameVersion) like this
{ "created":"2015-11-10 15:47:41.107Z",
"id_user" : "01",
"version" : "1",
"RecordName" : {"status" : "1", "name": "Paul"}
}
In my node application I have this for the schemas
var RecordNameVersion = new Schema({
_id : Number,
created : {type: Date, default: Date.now},
id_user : String,
version : { type: Number, min: 0 },
RecordName : {type: Schema.Types.ObjectId, ref: 'TaxonRecordName'}
});
var RecordName = new Schema({
trn_version : { type: Number, ref: 'RecordNameVersion' },
status : String,
name : String
});
When I try to post the Json, this error is generated.
"message": "RecordNameVersion validation failed",
"name": "ValidationError",
Is possible save all the JSON in one go? or is necessary put embedded the schema for Record Name?
I prefer different collections for RecordNameVersion y RecordName.
Or I should put the id for RecordNameVersion in the json for RecordName
Your error in saving RecordNameVersion is telling you the value of field
RecordName
wants to be a Reference, not some actual object. So synthesize its Reference as :
{
"_id": mongoose.Types.ObjectId("123456789000")
"created":"2015-11-10 15:47:41.107Z",
"id_user" : "01",
"version" : "1",
"RecordName" : mongoose.Types.ObjectId("123456789055")
}
then the corresponding RecordName save could be :
{
"_id": mongoose.Types.ObjectId("123456789055")
"status":"1",
"name" : "Paul",
"version" : "1",
"trn_version" : mongoose.Types.ObjectId("123456789000")
}
Notice the value of _id fields across the two documents

Parsing data and transferring it between views with SwiftyJSON and AlamoFire

I'm trying to deserialize a JSON object that is held in an Array. I'm using SwiftyJSON but the program is not behaving as I expected.
This is the array:
var GamesList = [JSON]();
The array holds my 2 JSON objects:
{
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "test1",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c8",
"game_idle_time" : 755858,
"opponent_left" : "3"
}, {
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "johannesswart",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c9",
"game_idle_time" : 755858,
"opponent_left" : "3"
}]hier is je gamestate: Optional({
"game_type" : "TRADITIONAL",
"game_player_winner" : "",
"game_state" : "STARTED",
"self_left" : "2",
"self_right" : "1",
"self_name" : "test2",
"opponent_right" : "1",
"opponent_name" : "testuser",
"game_guid" : "153fac87-bfc4-367f-41fa-944753dc32c9",
"game_idle_time" : 755858,
"opponent_left" : "3"
}
I create a new JSON object and fill it with a value of object 1 from the Array:
var gameState : JSON?;
self.gameState = GamesList[1];
When I print the entire self.gameState object to the console all is well and it looks like what I expected. However when I want to just use 1 value of this JSON object I can't seem to get it to work.
I tried with:
self.gameState["game_type"].string;
And:
var foo = JSON(self.gameState);
But this is both not compiling. What am I doing wrong?
I can see where this can be frustrating, but this is actually a pretty simple fix.
I had your same problem a while back when doing work with AlamoFire.
I can see why it's not compiling though, you are trying to retrieve a key out of an Array like:
self.gameState["game_type"]
but the Array type doesn't have key:value pairs, simple it is accessed via indexes:
self.gameState[1]
Step 1
So instead of an array, get your JSON into a dictionary. After that, follow these steps:
Make sure that your JSON data is being stored in a dictionary, like:
let jsonData: [String:String] = //your JSON
(use the var keyboard if you will be manipulating data in jsonData.
Step 2
After your JSON data is stored in a dictionary, simply do:
let gameState = jsonData["game_type"]!
You should not have a problem after that.
I hope I was able to shed some light, please comment if anything was unclear.