CJSON解析

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "cJSON.h"
#define PORT 80                   //http端口
#define ADDR "116.62.81.138"      //服务器ip
#define KEY "****"   //key密钥
#define LOCAL "beijing"           //要查询的地点 北京


void main(){
  
    //1.socket
    int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);


    struct sockaddr_in sock_addr;

    sock_addr.sin_family=AF_INET;
    sock_addr.sin_port=htons(PORT);
    sock_addr.sin_addr.s_addr=inet_addr(ADDR);

    //连接
    int ret = connect(tcp_socket,(struct sockaddr *)&sock_addr,sizeof(sock_addr));
    if(ret <0){
      fprintf(stderr,"connet error,errno:%d,%s",errno,strerror(errno));
      exit(-1);
    }
    char buf[1024]={0};
    //放入
    sprintf(buf,"GET https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c HTTP/1.1\r\n"
                "Host:api.seniverse.com\r\n"
                "\r\n"
            ,KEY,LOCAL);
    printf("\n1111111111111111111111111111111111111111111111\n"); 

    //发送
    send(tcp_socket,buf,sizeof(buf),0);

    bzero(buf,1024);

    //等待接收
    recv(tcp_socket,buf,sizeof(buf),0);
    printf("\n%s\n",buf);

    bzero(buf,1024);
    //等待接收
    recv(tcp_socket,buf,sizeof(buf),0);
    printf("%s\n",buf);
    cJSON * root = cJSON_Parse(buf);
    char * getjsonsting = cJSON_Print(root);

    printf("%s\n",getjsonsting);
    cJSON * results = cJSON_GetObjectItem(root, "results");
    cJSON * arrays0 = cJSON_GetArrayItem(results,0);
    //cJSON * result = cJSON_GetObjectItem(results, "result");

    cJSON * now = cJSON_GetObjectItem(arrays0, "now");
    cJSON * temperature = cJSON_GetObjectItem(now, "temperature");
    printf("1111111111111111111111111111111111111111\n");

    printf("\ntemperature:%s\n",temperature->valuestring);
    printf("\ntemperature:%d\n",atoi(temperature->valuestring));

    // char * getjsonsting = cJSON_Print(root);

    // printf("%s\n",getjsonsting);
    printf("1111111111111111111111111111111111111111\n");


    //创建一个json对象 {}
    cJSON *json_root = cJSON_CreateObject();

    cJSON *name = cJSON_CreateString("long");
    cJSON_AddItemToObject(json_root, "name", name);


    //创建一个数组[]
    cJSON *arrayname= cJSON_CreateArray();
    cJSON_AddItemToObject(json_root, "array", arrayname);


    cJSON *obj1 = cJSON_CreateObject();
    cJSON *obj2 = cJSON_CreateObject();
    cJSON_AddItemToArray(arrayname, obj1);
    cJSON_AddItemToArray(arrayname, obj2);


    cJSON * age = cJSON_CreateString("12");
    cJSON_AddItemToObject(obj1, "age", age);
    char * ptintjson = cJSON_Print(json_root);
    printf("%s\n",ptintjson);
    close(tcp_socket); // 程序退出前关闭套接字
}

 

posted @ 2025-06-19 21:46  记得要好好吃饭  阅读(9)  评论(0)    收藏  举报