Menu

[r3316]: / advanced / examples / json.c  Maximize  Restore  History

Download this file

117 lines (73 with data), 2.2 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
This example program demonstrates the JSON parsing and generating
capabilities of Xmlrpc-c.
The program reads JSON text from Standard Input and displays its value as
XML-RPC XML text. It then re-generates JSON from the intermediate
parsed information and displays that.
*/
#include <stdlib.h>
#include <stdio.h>
#include <xmlrpc-c/json.h>
#include <xmlrpc-c/util.h>
static void
dieIfFaultOccurred(xmlrpc_env * const envP) {
if (envP->fault_occurred) {
fprintf(stderr, "ERROR: %s (%d)\n",
envP->fault_string, envP->fault_code);
exit(1);
}
}
void
printAsXml(xmlrpc_value * const valP) {
xmlrpc_env env;
xmlrpc_mem_block * outP;
xmlrpc_env_init(&env);
outP = XMLRPC_MEMBLOCK_NEW(char, &env, 0);
dieIfFaultOccurred(&env);
xmlrpc_serialize_value(&env, outP, valP);
printf("XML-RPC XML:\n");
printf("%.*s\n",
XMLRPC_MEMBLOCK_SIZE(char, outP),
XMLRPC_MEMBLOCK_CONTENTS(char, outP));
XMLRPC_MEMBLOCK_FREE(char, outP);
xmlrpc_env_clean(&env);
}
void
printAsJson(xmlrpc_value * const valP) {
xmlrpc_env env;
xmlrpc_mem_block * outP;
xmlrpc_value * val2P;
xmlrpc_env_init(&env);
outP = XMLRPC_MEMBLOCK_NEW(char, &env, 0);
dieIfFaultOccurred(&env);
xmlrpc_serialize_json(&env, valP, outP);
dieIfFaultOccurred(&env);
printf("JSON:\n");
printf("%.*s\n",
XMLRPC_MEMBLOCK_SIZE(char, outP),
XMLRPC_MEMBLOCK_CONTENTS(char, outP));
XMLRPC_MEMBLOCK_FREE(char, outP);
xmlrpc_env_clean(&env);
}
int
main(int argc, const char *argv[]) {
xmlrpc_env env;
char buf[65536];
xmlrpc_value * valP;
size_t bytesReadCt;
xmlrpc_env_init(&env);
if (argc-1 > 0) {
fprintf(stderr, "This program has no arguments. "
"JSON input is from Standard Input\n");
exit(1);
}
bytesReadCt = fread(buf, 1, sizeof(buf)-1, stdin);
buf[bytesReadCt] = '\0';
valP = xmlrpc_parse_json(&env, buf);
dieIfFaultOccurred(&env);
printAsXml(valP);
printAsJson(valP);
xmlrpc_DECREF(valP);
xmlrpc_env_clean(&env);
return 0;
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.