【问题标题】:Parse JSON into a java object将 JSON 解析为 java 对象
【发布时间】:2016-05-14 20:31:31
【问题描述】:

您好,我有以下任务:

具有 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 列表并找到其中包含“名称”的 Object。

我认为问题是在不使用任何 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,我正在尝试创建一个 mini FSM (:)),它使用 for 循环解析字符串,并根据字符解析字符串或数字或数组标记。我正在使用非泛型映射,以便可以存储任何类型的对象。

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

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

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

请帮忙。

谢谢

【问题讨论】:

    标签: java json


    【解决方案1】:

    '我认为问题是要求在不使用任何 java 库的情况下解析 JSON' - 我个人认为它完全相反。

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

    我认为'通过注释定义如何将 JSON 定义到 Java 列表中并找到其中包含'名称'的对象。'强烈暗示将注释与杰克逊解析器一起使用 - 这将是解决此问题的标准方法。 Jackson annotations

    【讨论】:

    • 也许 OP 出于教育原因想要构建解析器,这是一个正当理由
    • 他被要求“读取 url”和“解析数据”,而不是“编写解析器”
    • 这是一个来自公司的面试问题,要求你编写自己的代码,而不是使用库/框架。
    • 如果他们是那种“类型”的公司,我会找别的地方工作。说真的,如果他们认为使用图书馆作为“作弊”,你不想知道。
    • 这是一个核心的java职位。所以他们会要求你发明不同的新算法和数据结构。他们问这种问题是为了看看你在核心java中的思维过程和实力。微软、亚马逊等大多数公司都进行这种面试。
    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多