PageRenderTime 39ms CodeModel.GetById 31ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

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