SwiftyJSON array elements? - json

I have tried finding how to work with SwiftyJSON arrays but nothing seems to work.
My function before using swift was:
json.brands.count
json.brands[0].name
json.brands[0].subname
json.brands[0].value
json.brands[1].name
json.brands[1].subname
json.brands[1].value
//Etc
Now I’m using:
json[“brands”][“name”].exists()
json[“brands”][“name”].string
But struggling to insert [0] [1] etc to make it work.
*I’m aware not to use 3rd party content if possible but my JSON api won’t work without a 3rd party. As there is 10 user inputs from a database which has thousands of dynamic entries to the JSON, so I can’t code them all, then there are objects which might be present and if they are present they might contain a value.
I tried the traditional swift json decoder approach but to catch all the errors with a dynamic nested JSON was giving me a headache.*

You can try this :
json[“brands”][0][“name”].exists()
json[“brands”][0][“name”].string
json[“brands”][1][“name”].exists()
json[“brands”][1][“name”].string
Hope it helps...

Related

Issue with ordering JSON keys when marshalling an ordered map in Golang

I have a requirement to iterate a given piece of JSON, and where an array contains a single item to convert that into a map. This is quite easy to do.
The catch is, I need to product a piece of JSON back to the client that is in the same order it was presented.
I have found some guides about using an OrderedMap, but that's inconsistent for me.
Sometimes I get the correct order, sometimes not.
https://go.dev/play/p/b9hmS9BEymy
Can anyone advise? From the logging it appear the issue may be with unmarshalling the incoming JSON
I am really reluctant to use structs, as the real JSON I need to process is very complex, and will need a huuuge amount of work as there are many variations.
Unmarshalling json will not respect order, as you use map[string]interface{}. Map in golang is a hashmap, so no surprise there. What you should do is create an UnmarshalJSON function as well and do custom unmarshalling, otherwise there is no way to preserve order.
You can use standard unmarshalling for every other type, except map, which should make it a lot easier. If you want details on how to do that, I can explain that too
If anyone ever stumbles across this, I was able to solve it by using this package
https://gitlab.com/c0b/go-ordered-json
I had to Unmarshall the JSON into an orderedmap so the map contained the keys in the order they were presented, and then I was able to work through them from there:
var om *OrderedMap = NewOrderedMap()
err := json.Unmarshal([]byte(input), om)

Swift unable to preserve order in String made from JSON for hash verification

We receive a JSON object from network along with a hash value of the object. In order to verify the hash we need to turn that JSON into a string and then make a hash out of it while preserving the order of the elements in the way they are in the JSON.
Say we have:
[
{"site1":
{"url":"https://this.is.site.com/",
"logoutURL":"",
"loadStart":[],
"loadStop":[{"someMore":"smthelse"}],
"there's_more": ... }
},
{"site2":
....
}
]
The Android app is able to get same hash value, and while debugging it we fed same simple string into both algorithms and were able to get out same hash out of it.
The difference that is there happens because of the fact that dictionaries are unordered structure.
While debugging we see that just before feeding a string into a hash algorithm, the string looks like the original JSON, just without the indentations, which means it preserves the order of items in it (on Android that is):
[{"site1":{"url":"https://this.is.site.com/", ...
While doing this with many approaches by now I'm not able to achieve the same: string that I get is different in order and therefore results in a different hash. Is there a way to achieve this?
UPDATE
It appears the problem is slightly different - thanks to #Rob Napier's answer below: I need a hash of only a part of incoming string (that has JSON in it), which means for getting that part I need to first parse it into JSON or struct, and after that - while getting the string value of it - the order of items is lost.
Using JSONSerialization and JSONDecoder (which uses JSONSerialization), it's not possible to reproduce the input data. But this isn't needed. What you're receiving is a string in the first place (as an NSData). Just don't get rid of it. You can parse the data into JSON without throwing away the data.
It is possible to create JSON parsers from scratch in Swift that maintain round-trip support (I have a sketch of such a thing at RNJSON). JSON isn't really that hard to parse. But what you're describing is a hash of "the thing you received." Not a hash of "the re-serialized JSON."

Deserialize an anonymous JSON array?

I got an anonymous array which I want to deserialize, here the example of the first array object
[
{ "time":"08:55:54",
"date":"2016-05-27",
"timestamp":1464332154807,
"level":3,
"message":"registerResourcePath ('', '/sap/bc/ui5_ui5/ui2/ushell/resources/')",
"details":"","component":"sap.ui.ModuleSystem"},
{"time":"08:55:54","date":"2016-05-27","timestamp":1464332154808,"level":3,"message":"URL prefixes set to:","details":"","component":"sap.ui.ModuleSystem"},
{"time":"08:55:54","date":"2016-05-27","timestamp":1464332154808,"level":3,"message":" (default) : /sap/bc/ui5_ui5/ui2/ushell/resources/","details":"","component":"sap.ui.ModuleSystem"}
]
I tried deserializing using CL_TREX_JSON_SERIALIZER, but it is corrupt and does not work with my JSON, here is why
Then I tried /UI2/CL_JSON, but it needs a "structure" that perfectly fits the object given by the JSON Object. "Structure" means in my case an internal table of objects with the attributes time, date, timestamp, level, messageanddetails. And there was the problem: it does not properly handle references and uses class description to describe the field assigned to the field-symbol. Since I can not have a list of objects but only a list of references to objects that solution also doesn't works.
As a third attempt I tried with the CALL TRANSFORMATION as described by Horst Keller, but with this method I was not able to read in an anonymous array, and here is why
My major points:
I do not want to change the JSON, since that is what I get from sap.ui.log
I prefere to use built-in functionality and not a thirdparty framework
Your problem comes out not from the anonymity of array, but from the awkwardness of SAP JSON (De)serializer, which doesn't respect double quotes, which enclose JSON attributes. The issue is thoroughly described in this answer.
If you don't want to change your JSON on-the-fly, the only way you have is to change CL_TREX_JSON_DESERIALIZER class like this.
/UI5/CL_JSON_PARSER parses JSONs with unknown format.
Note that it's got "for internal use" written on it so many times that you probably should take it seriously and clone its code to fixate it.

how to display json data got from json2 format

I get json data from Struts Action, like below:
I want to precoss this data in JSP page, but I tried to use .$each or attr, all does not woek, I use Json2.js JSON.stringfy() get these data, so how I can fet each key and value in it?
[{"agreementNumber":"161446628","employeeIndicator":"N","enrollmentSrc":"363","fepIndicator":"N","groupCancelDate":null,"groupCancelDateTime":0,"groupCnlDate":"","groupEffDate":"20070701","groupEffectiveDate":{"date":1,"day":0,"hours":0,"minutes":0,"month":6,"seconds":0,"time":1183262400000,"timezoneOffset":240,"year":107},"groupEffectiveDateTime":1183262400000,"groupName":"Westminster College","groupNumber":"01501701 ","index":"1","memberList":{"enrollmetSrc":"363","groupNumber":"01501701 ","memberList":[{"agreementNumber":"161446628","birthDate":{"date":10,"day":0,"hours":0,"minutes":0,"month":1,"seconds":0,"time":-217450800000,"timezoneOffset":300,"year":63},"birthDateTime":-217450800000,"cancelDate":null,"cancelDateTime":0,"classCode":" I3","effectiveDate":{"date":1,"day":0,"hours":0,"minutes":0,"month":6,"seconds":0,"time":1183262400000,"timezoneOffset":240,"year":107},"effectiveDateTime":1183262400000,"firstName":"KENNETH ","gender":"M","groupName":"","groupNumber":"01501701 ","lastName":"ROMIG ","medicareAdvantage":"","memberId":375315,"middleName":"J ","pin":"1","preTtlName":" ","relation":"Self","relationCode":"1","sucTtlName":" "},{"agreementNumber":"161446628","birthDate":{"date":23,"day":5,"hours":0,"minutes":0,"month":7,"seconds":0,"time":-200692800000,"timezoneOffset":240,"year":63},"birthDateTime":-200692800000,"cancelDate":null,"cancelDateTime":0,"classCode":" I3","effectiveDate":{"date":1,"day":0,"hours":0,"minutes":0,"month":6,"seconds":0,"time":1183262400000,"timezoneOffset":240,"year":107},"effectiveDateTime":1183262400000,"firstName":"KIMBERLY ","gender":"F","groupName":"","groupNumber":"01501701 ","lastName":"ROMIG ","medicareAdvantage":"","memberId":1424959,"middleName":"G ","pin":"3","preTtlName":" ","relation":"Spouse","relationCode":"2","sucTtlName":" "},{"agreementNumber":"161446628","birthDate":{"date":8,"day":1,"hours":0,"minutes":0,"month":0,"seconds":0,"time":631774800000,"timezoneOffset":300,"year":90},"birthDateTime":631774800000,"cancelDate":null,"cancelDateTime":0,"classCode":" I3","effectiveDate":{"date":1,"day":0,"hours":0,"minutes":0,"month":6,"seconds":0,"time":1183262400000,"timezoneOffset":240,"year":107},"effectiveDateTime":1183262400000,"firstName":"NICOLE ","gender":"F","groupName":"","groupNumber":"01501701 ","lastName":"CRUMBACHER ","medicareAdvantage":"","memberId":375314,"middleName":"A ","pin":"4","preTtlName":" ","relation":"Child","relationCode":"3","sucTtlName":" "},{"agreementNumber":"161446628","birthDate":{"date":7,"day":6,"hours":0,"minutes":0,"month":6,"seconds":0,"time":994478400000,"timezoneOffset":240,"year":101},"birthDateTime":994478400000,"cancelDate":null,"cancelDateTime":0,"classCode":" I3","effectiveDate":{"date":1,"day":0,"hours":0,"minutes":0,"month":6,"seconds":0,"time":1183262400000,"timezoneOffset":240,"year":107},"effectiveDateTime":1183262400000,"firstName":"NATHAN ","gender":"M","groupName":"","groupNumber":"01501701 ","lastName":"ROMIG ","medicareAdvantage":"","memberId":1424960,"middleName":"J ","pin":"6","preTtlName":" ","relation":"Child","relationCode":"3","sucTtlName":" "}]},"ownerCode":"HM"}]
Your json object has a complex structure so I am not going to write the function how to map it properly but I am going to give you some tools how to understand it better and work with it.
To see your json object more clearly use a an online json pareser http://json.parser.online.fr/ just paste your json object there and in the right you will see the tree like structure.
Here you can see examples how to access you json object properties jsfidle
I know that this is not what you want exactly but will help you build it.

Kohana ORM serialize columns, JSON and stdClass

I'm wondering how people are dealing with the stdClass that results from json_decode run on the columns in _serialize_columns in Kohana's ORM.
The problem I'm having is that I set the column as an array, which is serialized and is all good. Later, when I retrieve it, it comes back as a stdClass. This is all good for most things, but if I attempt use something like Arr::path() on that value, it of course can't deal with (a problem with array_shift I think).
One option I tried was casting the resulting value to an array, but this only works for the first level of the array. So, I then looped through the array casting everything to an array. This worked, but seems like a considerable hack.
What is everyone else doing to deal with this?
As a recommendation from #zeelot, I filed a ticket in Kohana's ticketing system: http://dev.kohanaframework.org/issues/4188
I also overrode the Kohana_ORM method _unserialize_value() as follows:
protected function _unserialize_value($value) {
return json_decode($value, TRUE);
}
Related discussion here: http://forum.kohanaframework.org/discussion/9465/orm-serialize-columns-json-and-stdclass