繁体   English   中英

将JSON解析为Java对象

[英]Parse JSON into a java object

您好,我有以下任务:

具有JSON对象的URL:

  - Write a program to read/write URL - Parse data in URL using JSON to JAVA Object - display 3 variables to user from the object - Find entity/list of object = Find object that has 'name' - Find Object that has 'author' - Find Object that has 'item' 

*通过注释定义如何将JSON定义到Java列表中,并找到其中具有“名称”的对象。

我认为问题是要在不使用任何Java库的情况下解析JSON。 到目前为止,我已经开发了以下代码:

class JSONObject {
    HashMap map = new HashMap();
}

public class SYW {
    public static String sampleUrl = "https://api.github.com/users/mralexgray/repos";
    public static Integer index = 1;

    public static void main(String[] args) {
        //String sampleJSON = fetchJSON(sampleUrl);
        JSONObject json = getJSONObject("{\"login\": \"mralexgray\",\"id\": 262517,\"avatar_url\": \"https://avatars.githubusercontent.com/u/262517?v=3\"}");
        // suppose there is a owner class
        populateJavaObject(json, Owner.class);
    }

    public static void populateJavaObject(JSONObject json, Class class1) {
        // TODO Auto-generated method stub
        Object obj = null;
        try {
            obj = class1.newInstance();
            Iterator it = json.map.keySet().iterator();
            while (it.hasNext()) {
                String key = (String)it.next();
                Object value = json.map.get(key);
                Field field = class1.getDeclaredField(key);
                field.setAccessible(true);
                if (value instanceof Integer) {
                    field.setInt(obj, (Integer)value);
                } else if (value instanceof String) {
                    field.setString(obj, (String)value);
                }
            }
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String getString(String jsonStr) {
        int i = index;
        StringBuffer buf = new StringBuffer();
        while (jsonStr.charAt(i) != '\"') {
            jsonStr.charAt(i);
            buf.append(jsonStr.charAt(i));
            i++;
        }
        index = i;
        return buf.toString();
    }

    public static JSONObject getJSONObject (String jsonStr) {
        StringBuffer buf = new StringBuffer();
        boolean isKey = true;
        String currentKey = "";
        Object currentValue = "";
        JSONObject json = new JSONObject();

        while (jsonStr.charAt(index) != '}') {
            if (jsonStr.charAt(index) == '\"') {
                index++;
                String token = getString(jsonStr);
                if (isKey) {
                    currentKey = token;
                } else {
                    currentValue = token;                       
                }
            } else if (Character.isDigit(jsonStr.charAt(index))) {
                Integer token = getNumber(jsonStr);
                currentValue = token;
            } else if (jsonStr.charAt(index) == '{') {
                currentValue = getJSONObject(jsonStr);
            } else if (jsonStr.charAt(index) == '[') {
                currentValue = getArray(jsonStr);
            } else if (jsonStr.charAt(index) == ':') {
                isKey = false;
            } else if (jsonStr.charAt(index) == ',' || jsonStr.charAt(index) == '}') {
                isKey = true;
                json.map.put(currentKey, currentValue);
            }
            index++;
        }

        return json;
    }

    private static ArrayList getArray(String jsonStr) {     
        ArrayList list = new ArrayList();
        while (jsonStr.charAt(index) != ']') {          
            index++;
        }
        return null;
    }

    private static Integer getNumber(String jsonStr) {
        // TODO Auto-generated method stub
        Integer num = 0;

        while (Character.isDigit(jsonStr.charAt(index))) {
            num = num * 10 + Integer.parseInt(jsonStr.charAt(index)+"");
            index++;
        }

        index--;

        return num;
    }

    public static Object parseJSON(String jsonStr) {
        Owner owner = new Owner();
        while (index <= jsonStr.length()) {
            if (jsonStr.charAt(index) == '{') {
                return getJSONObject(jsonStr);
            } else if (jsonStr.charAt(index) == '[') {
                return getArray(jsonStr);
            }
        }   

        return null;
    }

    public static String fetchJSON(String url) {
        String nextLine = "";
        try {
            URL sywURL = new URL(url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(sywURL.openStream()));
            StringBuffer buf = new StringBuffer();          
            while ((nextLine = reader.readLine()) != null) {
                buf.append(nextLine);
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return nextLine;
    }
}

我在这里所做的是我有一个JSONObject类,该类将JSON属性存储在地图中,然后我想使用反射来填充任何类。

为了解析JSON,我试图创建一个迷你FSM(:)),它使用for循环解析字符串,并基于字符解析字符串,数字或数组令牌。 我正在使用非通用映射,以便可以存储任何类型的对象。

我当时想也许我可以使用模板或某种模式,其中每个节点将具有递归结构或将成为叶节点。 但是我真的很困惑如何表示它,因为每个叶节点可以有一个属性和值。 我怎么能代表呢? 此外,这是唯一代表这一点的方法,还是到目前为止我所做的一切都朝着正确的方向迈进了?

其次,如果我解析对象,那么如何存储它们呢? 显然,任务是根据不同的属性值查找元素。 因此,我可以基于一个键创建一个哈希表来服务于这样的查询。 但是,如何创建有效的数据结构,使我可以基于不同的属性进行有效的查询?

第三,我不确定这是什么意思“通过注释定义如何将JSON定义到Java列表中并找到其中具有“名称”的对象。”

请帮忙。

谢谢

“我认为问题是要在不使用任何Java库的情况下解析JSON”-就我个人而言,它是完全相反的。

软件工程原则1是“不要再发明轮子”。

我认为“通过注释定义如何将JSON定义到Java列表中并找到其中具有“名称”的对象。 是在Jackson解析器中使用注释的有力提示-这将是解决此问题的标准方法。 杰克逊注释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM