/razpub/src/com/razie/pub/base/data/Pair.java

http://razpub.googlecode.com/ · Java · 54 lines · 37 code · 6 blank · 11 comment · 4 complexity · c8ec470998fc31f0afb17522d97336c4 MD5 · raw file

  1. /**
  2. * Razvan's public code. Copyright 2008 based on Apache license (share alike) see LICENSE.txt for
  3. * details.
  4. */
  5. package com.razie.pub.base.data;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10. /**
  11. * a simple pair of objects - use it as a quick tuple in lists or whatever...
  12. *
  13. * @author razie
  14. */
  15. @SuppressWarnings("unchecked")
  16. public class Pair<A, B> {
  17. public A a;
  18. public B b;
  19. public Pair(A a, B b) {
  20. this.a = a;
  21. this.b = b;
  22. }
  23. /** convert a list of pairs to java - the Pair.a must be String */
  24. public static JSONObject toJson(List<Pair> list, JSONObject obj) {
  25. try {
  26. if (obj == null)
  27. obj = new JSONObject();
  28. for (Pair p : list) {
  29. obj.put((String) p.a, p.b);
  30. }
  31. } catch (JSONException e) {
  32. throw new RuntimeException(e);
  33. }
  34. return obj;
  35. }
  36. /** convert a list of pairs to java - the Pair.a must be String */
  37. public static List<Pair> fromJson(List<Pair> list, JSONObject obj) {
  38. try {
  39. for (Iterator i = obj.keys();i.hasNext();) {
  40. String s=(String)i.next();
  41. list.add(new Pair(s, obj.get(s)));
  42. }
  43. } catch (JSONException e) {
  44. throw new RuntimeException(e);
  45. }
  46. return list;
  47. }
  48. }