简体   繁体   中英

iOS Swift: How to change the Response from server to Specific Format?

I stored the data from server to NSArray, Here I want change the current format to new format. But I don't know how to change the current format to new.Please help me for make the format. Here I have share the old format and new format as following.

This is old format received from Server.

{
{
“class” = “12”,
“section” = “A”,
“name” = “aathi”,
“mark” = “850”,
“school” = “ab matriculation school”,
“place” = “Chennai”
},
{
“class” = “12”,
“section” = “B”,
“name” = “ram”,
“mark” = “904”,
“school” = “ab matriculation school”,
“place” = “delhi”
},
{
“class” = “10”,
“section” = “C”,
“name” = “ashok”,
“mark” = “389”,
“school” = “psg hr sec school”,
“place” = “coimbatore”
},
{
“class” = “8”,
“section” = “B”,
“name” = “sundar”,
“mark” = “267”,
“school” = “govt hr sec school”,
“place” = “Madurai”
}

}

I want to change the new format like below.

{
{
“class” = “12”,
“section” = “A”,
“school” = “ab matriculation school”,
noncommondetails:{
        {
        “name” = “aathi”,
        “mark” = “850”,
        “place” = “Chennai”
        },
        {
        “name” = “ram”,
        “mark” = “904”,
        “place” = “delhi”
        }
    }
},
{
“class” = “10”,
“section” = “C”,
“school” = “psg hr sec school”,
noncommondetails:{
        {
        “name” = “ashok”,
        “mark” = “389”,
        “place” = “coimbatore”
        }
    },
},
{
“class” = “8”,
“section” = “B”,
“school” = “govt hr sec school”,
noncommondetails:{
        {
        “name” = “sundar”,
        “mark” = “267”,
        “place” = “Madurai”
        },
    }
}

}

您必须尝试https://github.com/Hearst-DD/ObjectMapper进行json对象映射。

The best design for what you are doing is to make models for your server response and then save those model objects in an array. That way you can change what you want.

Model for your old format:

struct Item {
    var aClass:String?
    var section:String?
    var name:String?
    var mark:String?
    var school:String?
    var place:String?
}

Now models for your new updated server response:

struct Item {
    var aClass:String?
    var section:String?
    var school:String?
    var nonCommonDetails : [NonCommenItem]?
}

struct NonCommenItem {
    var name:String?
    var mark:String?
    var place:String?
}

And then you can use it like:

let nonCommenItem1 = NonCommenItem(name: "aathi", mark: "850", place: "Chennai")
let nonCommenItem2 = NonCommenItem(name: "ram", mark: "904", place: "delhi")

let item1 = Item(aClass: "12", section: "B", school: "ab matriculation school", nonCommonDetails: [nonCommenItem1,nonCommenItem2])

I hope this solve your problem. If there is any confusion please ask. Good Luck :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM