How to convert JavaScript to Swift? (2), mainly about translating JavaScript parsing Json code into Swift? (How to automatically generate a HandyJson Model class from a Json string)

Translate JavaScript parsing JSON code to Swift

JSON parsing

{
    "error": 0."msg":"success"."data":[
        {
            "id": 27,"name":"Agreement and help."."sname":"xy"."parent_id":"0"."flag":"0"."created":"The 2017-01-15 09:47:09"."tag": 1, [5],"dated":"The 2017-01-15 16:31:32"}}]Copy the code

JavaScript parsing Json

In JavaScript, you only need one line of code to get “name”

var jsonObj = str.parseJSON();
jsonObj.data[0].name
Copy the code

Swift parsing Json

Common JOSN parsing libraries in Swift include HandyJson, ObjectMapper, SwiftyJson

SwiftyJson does not pre-define Model Class files, but it does not support Mode conversion, and the syntax of Json parsing is quite different from Js.

ObjectMapper Model class must implement the Mappable protocol, that is, implement init and mapping functions; Perfect for Alamofire. However, the mapping function is bloated and time-consuming.

HandyJson uses Swift reflection + memory assignment to construct Model instance, writing method is simple and can support JSON and Model mutual transfer requirements, and has been updated and maintained, parsing JSON syntax and Js differences are small;

Conclusion: Use HandyJson for Json parsing!

How to generate the Model class required for HandyJson?

I’ll just paste the code here…

// Generate Swift Model file var generateCode =function (jsonString, className) {
    var k = ""; // Uppercase var toUpperVar =function (a) {
        return a.replace(/\b[a-z]/g, function (a) {
            returna.toUpperCase() }) }; Var toLowerVar =function (a) {
        return a.replace(/\b[a-z]/g, function (a) {
            returna.toLowerCase() }) }; // Determine whether there is a nested Model var q =function(a) {// Check if it is an arrayreturn a instanceof Object ? a.constructor.prototype.hasOwnProperty("push") :! 1}; var r =function(a) {// Check if it is an arrayreturna instanceof Object ? ! a.constructor.prototype.hasOwnProperty("push") :! 1}; // generate class var getClass =function (a, d) {
        let required = "\n required init() {}"
        return "class " + a + ": HandyJSON {\n" + d + required + "\n}"}; // Generate the variable var getVar =function (a, d) {
        return " var " + d + ":" + a + "\n"}; // Swift parse json var generateSwift =function (a, d) {
        var c = "";
        if (q(a)) {
            if (a.length > 0) {
                for (var e = a[0], f = a.length - 1; 0 <= f; f--) {
                    var b = a[f];
                    q(b) ? b.length > e.length && (e = b) :
                        r(b) && Object.keys(b).length > Object.keys(e).length && (e = b)
                }
                c += generateSwift(e, d)
            }
        } else if (r(a)) for (e in a) {
            b = a[e];
            var h = toUpperVar(e);
            f = toLowerVar(e);
            if(q(b)) { var g; // Get the first 0 < b.length && (g = b[0]);if ("string" === typeof g) {
                    c += getVar("[String]!", f);
                } else {
                    if ("number"=== typeof g) {// Determine floating point numbersif (0 <= b.toString().indexOf(".")) {
                            c += getVar("[Float]!", f);
                        } else {
                            c += getVar("[Int]!", f); }}else if ("boolean" === typeof g) {
                        c += getVar("[Bool]", f)
                    } else if ("object" === typeof g) {
                        h += "Item";
                        c += getVar("[" + h + "]!", f);
                        b = generateSwift(b, e);
                        if (0 < k.length) {
                            k += "\r\n\r\n" + getClass(h, b)
                        } else {
                            k = getClass(h, b)
                        }
                    }
                }
            } else {
                if (r(b)) {
                    b = generateSwift(b, e)
                    c += getVar(h, f)
                    k = 0 < k.length ? k + "\r\n\r\n" + getClass(h, b) : getClass(h, b)
                } else {
                    if ("string" === typeof b) {
                        c += getVar("String = ''", f)
                    } else if ("number"=== typeof b) {// Determine floating point numbersif (0 <= b.toString().indexOf(".")) {
                            c += getVar("Float = 0.0", f)
                        } else {
                            c += getVar("Int = 0", f)
                        }
                    } else if ("boolean" === typeof b) {
                        c += getVar("Bool = false", f)
                    }
                }
            }
        } else alert("key = " + d); return c
    };

    var swiftFunc = function (a, d) {
        k = ""
        0 == d.length && (d = "DefaultModelName");
        var c = generateSwift(a, d);
        k = 0 < k.length ? k + "\r\n\r\n" + getClass(d, c) : getClass(d, c);
        return k
    };

    return {
        swiftModel: function () {
            var d = eval("(" + jsonString + ")");
            return swiftFunc(d, toUpperVar(className))
        }
    }

};

exports.generateCode = generateCode;
Copy the code

How to call?

var generateModel = require('./generateModel.js');
var fs = require("fs")
const { exec } = require('child_process');

var d = "{" error" : 0, 'MSG' : 'success' and 'data' : [{" id ": 27, 'name' : 'agreement and help', 'sname' : 'y', 'parent_id' : '0', 'flag' : '0', 'created' : '2017-01-15 09:47:09','tag':[1, 5], 'dated': '2017-01-15 16:31:32'}]}"

var fileName = "testModel"
var code = generateModel.generateCode(d, fileName).swiftModel();
console.log(code)


fs.writeFile('./Swift_Code/' + fileName + '.swift', code,  function(err) {
    if (err) {
        returnconsole.error(err); }}); // Format the codeexec('swiftformat ./Swift_Code/' + fileName + 'swift -- swiftversion 4.2', (err, stdout, stderr) => {
     if(err) {
         return; }})Copy the code

Execute the above code to generate the following file:

class DataItem: HandyJSON {
    var id: Int = 0
    var name: String = ""
    var sname: String = ""
    var parent_id: String = ""
    var flag: String = ""
    var created: String = ""
    var tag: [Int]!
    var dated: String = ""

    required init() {}
}

class TestModel: HandyJSON {
    var error: Int = 0
    var msg: String = ""
    var data: [DataItem]!

    required init() {}}Copy the code

In order to avoid the Crash of the Optional resolution, I have assigned a default value, which is always a bit wrong.

Translate JavaScript parsed Json code to Swift

With the Model generated, it’s much easier to parse JavaScript Json code into Swift

Jsonobj.data [0]. Name can even be translated directly without modification ~

Finally, post the code to generate HandyJson

How do I convert JavaScript to Swift? (a)

How do I convert JavaScript to Swift? (2)