You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

testReplaceExisting.c 1.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stddef.h>
  4. #include <string.h>
  5. #include "json.h"
  6. int main(int argc, char **argv)
  7. {
  8. MC_SET_DEBUG(1);
  9. /*
  10. * Check that replacing an existing object keeps the key valid,
  11. * and that it keeps the order the same.
  12. */
  13. json_object *my_object = json_object_new_object();
  14. json_object_object_add(my_object, "foo1", json_object_new_string("bar1"));
  15. json_object_object_add(my_object, "foo2", json_object_new_string("bar2"));
  16. json_object_object_add(my_object, "foo3", json_object_new_string("bar3"));
  17. const char *original_key = NULL;
  18. int orig_count = 0;
  19. json_object_object_foreach(my_object, key, val)
  20. {
  21. printf("Key at index %d is [%s]\n", orig_count, key);
  22. orig_count++;
  23. if (strcmp(key, "foo2") != 0)
  24. continue;
  25. printf("replacing value for key [%s]\n", key);
  26. original_key = key;
  27. json_object_object_add(my_object, key, json_object_new_string("zzz"));
  28. }
  29. printf("==== second loop starting ====\n");
  30. int new_count = 0;
  31. int retval = 0;
  32. json_object_object_foreach(my_object, key2, val2)
  33. {
  34. printf("Key at index %d is [%s]\n", new_count, key2);
  35. new_count++;
  36. if (strcmp(key2, "foo2") != 0)
  37. continue;
  38. printf("pointer for key [%s] does %smatch\n", key2,
  39. (key2 == original_key) ? "" : "NOT ");
  40. if (key2 != original_key)
  41. retval = 1;
  42. }
  43. if (new_count != orig_count)
  44. {
  45. printf("mismatch between original count (%d) and new count (%d)\n",
  46. orig_count, new_count);
  47. retval = 1;
  48. }
  49. return 0;
  50. }