开发者

iPhone: How to programmatically create a json file and insert the data obtained from my Sqlite database into it?

I want to get data from my Sqlite database and put it into this JSON file.

How can I create a json file and insert the data obtained from my database into the JSON file?

I want data in JSON file in this format:

{

"data": [
    {
        "data": [
            null,
            null,
            30,
            45,
            69,
            70,
            65
        ],
        "title": "title5" 
    },
    {
        "data": [
            null,
            5,
            10,
            15,
            22,
            30 
        ],
        "title": "title4" 
    },
    {
        "data": [
            40,
            55,
        ],
        "title": "title3" 
    },
    {
          "data": [
              null,
            89,
            90,
            85
        ],
        "title": "title2" 
    },
    {
        "data": [
            66,
            77,
            55,
            开发者_JAVA技巧33,
            50,
            -6,
            -8
        ],
        "title": "title1" 
    } 
],
 "x_labels": [
    6,
    7,
    8,
    9,
    10,
    11,
    12
]
}

How can I do this?


Create Obj C object reading data from your sqlite database. Say

@interface Data:NSObject {
  NSArray *data;
  NSString *title;
}

NSArray *dataArray; // array of data filled with all Data object read from database.
  1. Use JSON Framework to convert all data to JSON string. Notice that for the Data object, you have to override the proxyForJson method, since its a user defined object.

You can make a JSON string from an object ,

SBJsonWriter *writer = [SBJsonWriter new];
NSString *jsonString = [writer stringWithObject:dataArray];
[writer release];

I am not sure if it works directly for array, if not, encapsulate your dataArray in anotherObject, and send that object to this JSON writer.

Write the JSON string to a file.

 [jsonString writeToFile:path atomically:YES encoding:NSASCIIStringEncoding 
             error:nil]


In order to create a json output what you can do is first get the sqlite data in some array or plist or dictionary etc, then use the function JSONRepresentation to display the JSON output for the same, here's a sample code that might help you

-(void)create_Json
{
    NSArray *arr = [[NSArray alloc] initWithObjects:@"Ravi",@"Riki",@"Faisal",@"Sanjay", nil];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:arr forKey:@"Friends"];

    NSLog(@"JSON representation for dictionary is %@",[dict JSONRepresentation]);

}

Make sure that you are importing the JSON libraries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜