hide .json files when included in Cocoa Touch Framework - json

I would like to release a cocoa touch framework including some json files which contain logic I don't want the framwork's user to see; unfortunately inside the .framework file there is still the json visible.
I thought about including it in a swift file:
struct JsonProvider {
static let json = "..."
}
but my json is that large that the file isn't usable any more. I didn't find a solution to command line compile and then include it.
Is there a solution to one of the two problems, i.e.
hide the json inside the framework or
precompile a swift file and then add it to the framework?

The answer to this really depends on how secure you need the file to be. Nothing is going to be 100% secure but you can make it more or less difficult for an attacker to gain access.
Option A: Hide the file
Add a '.' at the beginning of the file name, which will hide it from those browsing the directory that don't know about hidden files.
Caveats:
Anyone with knowledge of hidden files can figure this out.
Option B: Obfuscate
Encode your file, using Base64 or other encoding methods.
Caveats:
Only deters the lazy/mildly curious. Encodes are easy to defeat.
Option C: Encryption or storing in code
Encrypt the file using a symmetrical algorithm such as AES and store the cipher in code.
Alternatively, remove the json file and create a variable in code with a string that holds the json.
var myJson = """
{
"jsonData": "value"
}
"""
Caveats:
Code can be decompiled to reveal hardcoded strings, but it's difficult. Someone would have to gain access your .ipa file which is protected by Apple's DRM. You could also opt to encode the string, but if someone is already decompiling your code then they can figure out how to defeat obfuscation.
Option D: Don't include the file at all
This is a pretty broad topic outside the scope of your question, but essentially you host your file somewhere. Where and how you do this again depends on how secure you need the data to be. Ideally serving the data over HTTPS and blocking self-signed certificates from being used in your app so that it can't be proxied (ie man in the middle).
URLSession already does a pretty good job of this out of the box, but you could take it even further by using certificate pinning: https://developer.apple.com/news/?id=g9ejcf8y
Essentially you create certificate configurations on your server and bundle the public keys in your app, the connection will be refused unless the pinning requirements are met. Caveat is that you have to update your app whenever your certificates change.

There are many ways:
You can encrypt that file end decrypt again before using.
Change json file type to picture or something else to make sure no one know this is JSON file.

You can add json file content to sources as base64 encoded string.
struct JSONFiles {
internal static let fileOneBase64String = "iVBORw0KGgoAAAANSUhEUgAAAMEAAADLCAYAAADX..."
static var fileOneJSON: [String: Any] {
let data = Data(base64Encoded: fileOneBase64String)!
return try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
}
}
You can use it later anywhere in you framework by
print(JSONFiles.fileOneJSON)
Hope it help you
UPDATE:
Why as base64 encoded string?
The main benefit base64 encoded string - you don't need to escape special symbols contained in JSON string. Don't need to remove new line symbols/intendation symbols from json string before add to swift source file.
See example
let string: String = "{ \"name\":\"John\", \"email\": \"hello#stackoverflow\" \"age\":30, \"car\":null }"
But if json is more complex? If it contains 10 nested levels, arrays, dictionaries?
You can cover by UnitTests that value contained in fileOneBase64String can be decoded to JSON object
import XCTest
#testable import MyAwesomeFramework
class FrameworkTests: XCTestCase {
func testThatBase64EncodedJSONStringCanBeDecoded() {
let data = Data(base64Encoded: JSONFiles.fileOneBase64String)
XCTAssertNotNil(data, "Unable to convert base64 string to Data")
do {
_ = try JSONSerialization.jsonObject(with: data, options: [])
} catch {
XCTFail("Expected decoded JSON ")
}
}
}

Related

Elm Json Decode - do nothing, get original string back

I'm using the-sett/elm-aws-core to get information from the AWS API, which unfortunately is very very inconsistent. Most of the endpoints return JSON and that works fine with that lib, which takes a JSON Decoder to make a request, but the EC2 endpoint returns XML (because why not).
The lib doesn't have any options not to decode JSON as far as I can tell, which does not work at all :
let ec2 region = Service.defineRegional "ec2" "2016-11-15" Service.QUERY Service.SignV4 (Service.setXmlNamespace "https://ec2.amazonaws.com/doc/2016-11-15/") region in
let params = [("Action", "DescribeImages"), ("Version", "2016-11-15"), ("Owner.1", "self")] in
Http.request "DescribeImages" GET "/" Http.emptyBody JSONDECODERHERE |> Http.addQuery params |> Http.send (ec2 region) creds |> Task.attempt msg
Failed : Problem with the given value:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeImagesResponse .......
As you can see in there you need to pass a JSON Decoder to Http.request, but that, of course, fails when receiving XML. Is there a way to build a "fake" JSON decoder that would actually do nothing and just pass on the raw string? I tried using Decode. string but that's still actually decoding it, which fails. If there is a way I could then run an XML decoder manually on it in my update function, which would be fine.
Thank you
It's not possible to make a "fake" decoder that does what you want, because the problem isn't with the decoding. The problem is with the parsing, which is done before decoding. Parsing is the process of converting the string into a data structure typically called an Abstract Syntax Tree (AST), but since Elm compiles to JavaScript and JSON is also a subset of JavaScript the parse result of is really just a JavaScript object. Decoding is the process of turning that untyped data structure into a properly typed data structure.
It is therefore not possible to accomplish what you want with this API. Most likely you'll need to build the http request yourself and use elm/http directly.

scala akka-http - complete get request with a pre-built json object and stream it

I am trying to complete a get request by returning a pre-built JsonArray, and also find a way to stream it. I can easily complete the request without any errors and return Json if I convert the JsonArray to string, like so:
get {
path("getJsonData") {
parameterMap {
params =>
complete(HttpEntity(ContentTypes.`application/json`, myJsonArray.toString))
}
}
}
However, I would like to avoid converting to string, and be able to stream the JsonArray, because the resulting JsonArray can be very large in some cases.
JsonArray is created from scratch from individual JsonObjects, and I do not use case classes, so I could not use the standard approaches I found in the documentation.
I am new to Akka Http and not sure if there is a simple way to solve this problem, would appreciate some help.
With the below you will be streaming each element of your JSON array in a separate HTTP chunk.
complete(HttpEntity(ContentTypes.`application/json`,
Source(myJsonArray.elements).map(j ⇒ ByteString(j.prettyPrint))))
Note that:
The choice of prettyPrinting the JSON can be revisited to fit your needs.
You can adjust the size of your frame by batching elements together using the Akka Streams API.

Have I any opportunity to attach decode json struct to http.Request variable in go lang

I have a situation some methods use one link to request *http.Request. In it body it contains json. And I need to get different data from that json. But I don't want to decode json every time in every method again and again. Can I decode once and attach the link of struct or json (in string) to request. I try to find the solution but I didn't found anything. I know that I can create my own functional for this, but I think that such packages like "*http.Request" or "github.com/gorilla/mux" should have such functionality from the box. Anyone known?

Swift Generic Function Returning New Object

I am trying to make a generic function that returns objects obtained via a REST API JSON response. I want to provide the type with a generic, have it submit the request/parse the JSON, and return a list of objects of the provided type (such as Item). I have the part of getting the JSON response, but using generics is new for me. Here's a pseudocode of the situation holding me up:
class Model {
func setPropertiesFromJSON(data: NSData) {
// Lookup property names of object and set from JSON fields.
}
}
class Item : Model {
var a
var b
}
class RestEndpoint {
func getModels<T>() -> [T] {
let data: NSData = ... // Submit GET request and receive JSON data.
var models = [T]()
for objectData in data {
// How to create newobj as T (subtype of Model), set its properties,
// and add it to models array?
// let newobj: T as? TrackminiModel = T()
// newobj.setPropertiesFromJSON(objectData)
// models.append(newobj)
}
return models
}
}
let restEndpoint = RestEndPoint()
var items: [Item] = restEndpoint.getModels<Item>()
The commented out code is very incorrect but that is the goal. Any thoughts on how to do this?
From your question it sound like what your are interested in is something that is a fairly common need. The ability to communicate with a backend server using a Restful API. You can continue down the path you seem to be heading an create a lot of code to accomplish this, and this answer will not provide much help in that direction.
However I would like to point you to two open source libraries, ObjectMapper, which I think addresses your question. Here is a brief description of ObjectMapper (from its github page).
ObjectMapper is a framework written in Swift that makes it easy for
you to convert your Model objects (Classes and Structs) to and from
JSON.
The second project is AlamofireObjectMapper which I think in the end might be exactly what you are looking for. Here is a brief description from that projects githup page.
An extension to Alamofire which automatically converts JSON response
data into swift objects using ObjectMapper.
All of this is built on top of Alamofire which handle all the details of communicating with Restful API's.
Again here is a brief description of Alamofire.
Alamofire is an HTTP networking library written in Swift.
Chainable Request / Response methods
URL / JSON / plist Parameter Encoding
Upload File / Data / Stream
Download using Request or Resume data
Authentication with NSURLCredential
HTTP Response Validation
Progress Closure & NSProgress
cURL Debug Output
Comprehensive Unit Test Coverage
Complete Documentation
You might feel like picking up other libraries to accomplish some task is "cheating" you out of an opportunity to learn how to do something yourself, but there are still plenty of challenges in making an app. Some would say not taking advantage of these open source libraries is "undifferentiated heavy lifting"

How to parse the JSON response in Blackberry/J2ME?

I want to parse the response coming from the server in JSON format. I have done some googling but i can't find any library or jar kind of thing.
Everywhere there is provided open source code as zip file.
How can i achieve this? if there is no jar available for blackberry then how to use that open source code in my application??
There is an open source JSON for J2ME API on Mobile and Embedded Application Developers Project
Also you can download JSON ME (Zip file) at JSON.org not supported anymore. But you can get it from here.
I believe you can simply copy content of json project src folder to your Blackberry project src folder, refresh it in eclipse package explorer and build it.
See for details: Using JavaScript Object Notation (JSON) in Java ME for Data Interchange
I am developing a Blackberry client application and I confronted the same problem. I was searching for JSON way of parsing the response which I get from the server. I am using Eclipse plug-in for BB as IDE and it comes with BB SDK including the ones for JSON.
The easiest answer to this question is that:
Initially do not forget to use this import statement:
import org.json.me.JSONObject;
Then assign your JSON formatted response from the server to a String variable:
String jsonStr = "{\"team\":\"Bursaspor\",\"manager\":\"Ertuğrul Sağlam\",\"year\":\"2010\"}";
Create a JSONObject:
JSONObject obj = new JSONObject(jsonStr);
i.e. if you want to use the value of the "team" field which is "Bursaspor" then you should use your JSONObject like this:
obj.getString("team")
This call will return the string value which is "Bursaspor".
P.S: I inspired this solution from this site which simply explains the solution of the same problem for Android development.
http://trandroid.com/2010/05/17/android-ile-json-parse-etme-ornegi-1/
When you got response string then use this code
try {
JSONObject jsonres = new JSONObject(jsons);
System.out.println("Preview icon from jsonresp:"+jsonres.getString("mydata"));
} catch (JSONException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
one thing jsons is your response string which is in json format & mydata your key of data so you can get your data from JSONObject. Thnks
chek this post to find out how to get JSONME source from SVN:
http://www.java-n-me.com/2010/11/how-to-import-source-code-from-svn-to.html
Hope it helps someone.
You can also try :
http://pensivemode.fileave.com/verified_json.jar
I was also looking for a jar version of json (to link along my lib) :
https://radheshg.wordpress.com/tag/json/
but it seems not portable :
Building example
C:\Program Files (x86)\Research In Motion\BlackBerry JDE 4.5.0\bin\rapc.exe -quiet import="C:\Program Files (x86)\Research In Motion\BlackBerry JDE 4.5.0\lib\net_rim_api.jar";lib\${PROJECT}.jar;lib\json.jar codename=example\example example\example.rapc warnkey=0x52424200;0x52525400;0x52435200 Y:\src\${PROJECT}-java.git\example\src\mypackage\MyApp.java Y:\src\${PROJECT}-java.git\example\src\mypackage\MyScreen.java
tmp3139/org/json/me/JSONArray.class: Error!: Invalid class file: Incorrect classfile version
Error while building project
http://supportforums.blackberry.com/t5/Java-Development/JSON-library/m-p/573687#M117982
So far JSON.simple is looking like a great viable option.
JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=parser.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();