json.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. This example program demonstrates the JSON parsing and generating
  3. capabilities of Xmlrpc-c.
  4. The program reads JSON text from Standard Input and displays its value as
  5. XML-RPC XML text. It then re-generates JSON from the intermediate
  6. parsed information and displays that.
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <xmlrpc-c/json.h>
  11. static void
  12. dieIfFaultOccurred(xmlrpc_env * const envP) {
  13. if (envP->fault_occurred) {
  14. fprintf(stderr, "ERROR: %s (%d)\n",
  15. envP->fault_string, envP->fault_code);
  16. exit(1);
  17. }
  18. }
  19. void
  20. printAsXml(xmlrpc_value * const valP) {
  21. xmlrpc_env env;
  22. xmlrpc_mem_block out;
  23. xmlrpc_env_init(&env);
  24. XMLRPC_MEMBLOCK_INIT(char, &env, &out, 0);
  25. dieIfFaultOccurred(&env);
  26. xmlrpc_serialize_value(&env, &out, valP);
  27. printf("XML-RPC XML:\n");
  28. printf("%.*s\n",
  29. XMLRPC_MEMBLOCK_SIZE(char, &out),
  30. XMLRPC_MEMBLOCK_CONTENTS(char, &out));
  31. XMLRPC_MEMBLOCK_CLEAN(char, &out);
  32. xmlrpc_env_clean(&env);
  33. }
  34. void
  35. printAsJson(xmlrpc_value * const valP) {
  36. xmlrpc_env env;
  37. xmlrpc_mem_block out;
  38. xmlrpc_value * val2P;
  39. xmlrpc_env_init(&env);
  40. XMLRPC_MEMBLOCK_INIT(char, &env, &out, 0);
  41. dieIfFaultOccurred(&env);
  42. xmlrpc_serialize_json(&env, valP, &out);
  43. dieIfFaultOccurred(&env);
  44. printf("JSON:\n");
  45. printf("%.*s\n",
  46. XMLRPC_MEMBLOCK_SIZE(char, &out),
  47. XMLRPC_MEMBLOCK_CONTENTS(char, &out));
  48. XMLRPC_MEMBLOCK_CLEAN(char, &out);
  49. xmlrpc_env_clean(&env);
  50. }
  51. int
  52. main(int argc, const char *argv[]) {
  53. xmlrpc_env env;
  54. char buf[1024];
  55. xmlrpc_value * valP;
  56. size_t bytesRead;
  57. xmlrpc_env_init(&env);
  58. if (argc-1 > 0) {
  59. fprintf(stderr, "This program has no arguments. "
  60. "JSON input is from Standard Input\n");
  61. exit(1);
  62. }
  63. bytesRead = fread(buf, 1, sizeof(buf), stdin);
  64. buf[bytesRead] = '\0';
  65. valP = xmlrpc_parse_json(&env, buf);
  66. dieIfFaultOccurred(&env);
  67. printAsXml(valP);
  68. printAsJson(valP);
  69. xmlrpc_DECREF(valP);
  70. xmlrpc_env_clean(&env);
  71. return 0;
  72. }