将JSON解析为java对象

将JSON解析为java对象

本文介绍了将JSON解析为java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以下任务:

            - 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列表并找到其中包含'name'的Object。

*Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it.

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

I think the question is asking to parse the JSON without using any java library. So far I have developed the following code:

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属性存储在地图中然后我想使用反射来填充任何类。

What I am doing here is I have a JSONObject class which stores the JSON attributes in a map then I want to use reflection to populate any class.

为了解析JSON,我试图创建一个迷你FSM(:) ),使用for循环解析字符串,并根据字符解析字符串或数字或数组标记。我正在使用非泛型地图,以便我可以存储任何类型的对象。

For parsing the JSON, I am trying to create a mini FSM ( :) ), which parses the string using a for loop and based on the character it either parses the string or number or array token. I am using a non-generic map so that I can store object of any type.

我在想我可以使用模板或每个节点都有的模式递归结构或将是叶节点。但我真的很困惑如何表示,因为每个叶节点可以有一个属性和值。我怎么能代表那个?除此之外,这是表示我或目前为止所做的任何事情的唯一方法是朝着正确的方向吗?

I was thinking may be I can use template or something pattern where each node will have a recursive structure or will be a leaf node. But I am really confused how to represent that because each leaf node can have one attribute and value. How can I represent that? Besides Is this the only way to represent that or whatever I have done so far is in the right direction?

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

Secondly, if I parse the objects, then how can I store them? Obviously the task is to find elements based on different attribute values. So I can create probably a hashmap based on one key to serve the one such query. But then how can I create an efficient data structure that will allow me efficiently query based on different attributes?

第三,我不确定这是什么意思通过注释定义如何将JSON定义到Java列表中并找到其中包含'name'的Object。

Thirdly, I am not sure what this means "Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it."

请帮忙。

谢谢

推荐答案

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

'I think the question is asking to parse the JSON without using any java library' - personally I take it as being the complete opposite.

软件工程原理1是'不要重新发明轮'。

Software engineering principle number 1 is 'Don't reinvent the wheel'.

我认为'通过注释定义如何将JSON定义为Java列表并找到具有'名称'的对象使用Jackson解析器的注释是一个强烈的提示 - 这将是解决这个问题的标准方法。

I think 'Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it.' is a strong hint to use the annotations with the Jackson parser - which would be the standard way to attack this problem. Jackson annotations

这篇关于将JSON解析为java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:35