Swift Nsjsonserialization JSON parsing

Source: Internet
Author: User

Here are the parsing, generation methods

func jsonparse () {

/****************************************** parsing json type ************************************** /

let jsonfile = nsbundle. Mainbundle(). Pathforresource("Jsonparsefile", OfType: "Geojson")

let jsondata = nsdata. Datawithcontentsofmappedfile(jsonfile!) As nsdata

var errorread:nserror?

var jsonparse = nsjsonserialization. Jsonobjectwithdata(Jsondata, Options: nsjsonreadingoptions. Mutableleaves, Error: &errorread) as nsdictionary

if errorread==nil {

let itemCount = Jsonparse. Objectforkey("ItemCount") as nsstring

println(" total data : \ (itemCount)")

let itemarray = Jsonparse. Objectforkey("Info") as nsarray

println(" current array : \ (ItemArray. Count)")

let dataarray = Jsonparse. Objectforkey("Info") as nsarray

for mandic in dataarray{

let name = Mandic.objectforkey ("name") as nsstring

println(" data array : \ (name)")

}

}else{

println("JSON not valid , parsing failed ")

}

/****************************************** converted to JSON type ********************************* *****/

Let writeJsonArray1 = ["1","2","3"] /c2>

let writeJsonArray2 = ["4","5","6"]

let writejsondictory = [" array 1": WriteJsonArray1," array 2": WriteJsonArray2]

let jsonformater = nsjsonserialization. Isvalidjsonobject(writejsondictory)

if jsonformater {

println(" is standard JSON format ")

}else{

println(" non-standard JSON format ")

}

var errorwrite:nserror?

var jsonwritedata = nsjsonserialization. Datawithjsonobject(writejsondictory, Options: nsjsonwritingoptions. prettyprinted, Error: &errorwrite)

var lastparse = nsstring(data:jsonwritedata!, Encoding: nsutf8stringencoding)

println("Convert to json type \ n\ (lastparse)")  

}

Swift Nsjsonserialization JSON parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.