递归方法返回存储为JSON文件的不同对象 [英] Recursive method to return different objects stored as JSON files

查看:72
本文介绍了递归方法返回存储为JSON文件的不同对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个答案,我认为它适用,但有点麻烦。

I found this answer and I think it applies, but with a little twist.

如何从Java方法返回多个对象?

I有两个使用YML子​​集的JSON格式文件,其中一个是设备列表,另一个是列出特定类型设备属性的文件。

I have two JSON formatted files using the YML subset, one of which is a list of devices, and the other is a file that lists the attributes of a particular type of device.

将Device实例列表分成一个文件和另一个文件中的属性的选择是允许设备制造商更改属性,而不必返回并重写/重新编译硬编码属性。

The choice of dividing up the list of Device instances into one file and the attributes in another file is to allow the Device manufacturer to change the attributes without having to go back and rewrite/recompile hard coded attributes.

在任何情况下,我都可以使用两个不同的JSONParser调用,然后最后将属性列表添加到Device对象,但是这个解决方案似乎是浪费代码,除了设置值的while循环的内部部分,它们完全相同。

In any case, I could use two different calls to the JSONParser and then add the list of attributes to the Device object in the end, but that solution seems like a waste of code since, except for the inner part of the while loop where the values are set, they do exactly the same thing.

我认为像Ruby-ish Yield这样的东西可能在内循环中起作用,但不确定它是否存在于Java中。

I thought something like a Ruby-ish Yield might do the trick in the inner loop, but not sure if this exists in Java.

所以,没有太多的麻烦,这里是代码:

So, without much further ado, here is the code:

// Import the json simple parser, used to read configuration files
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.*;

public  class LoadJson {

    private String path = "";
    private String fileType = "";

    //public LoadJson(String path, String fileType){

        //this.path = path;
        //this.fileType = fileType;

    //}

    public static Device openJSON(String fileType, String deviceName) {
        JSONParser parser = new JSONParser();
        Device myDevice = new Device();

        ContainerFactory containerFactory = new ContainerFactory(){
            public List creatArrayContainer() {
              return new LinkedList();
            }

        public Map createObjectContainer() {
          return new LinkedHashMap();
        }

      };

      try {
            File appBase = new File("."); //current directory
            String path = appBase.getAbsolutePath();
            System.out.println(path);

            Map obj = (Map)parser.parse(new FileReader(path+fileType),containerFactory);

            Iterator iter = obj.entrySet().iterator();

            //Iterator iterInner = new Iterator();

            while(iter.hasNext()){
                //LinkedList entry = (LinkedList)iter.next();
                LinkedList myList = new LinkedList(); 
                Map.Entry entry = (Map.Entry)iter.next();

                myList = (LinkedList) (entry.getValue());

                Iterator iterate = myList.iterator();
                while (iterate.hasNext())
                {
                    LinkedHashMap entry2 = (LinkedHashMap)iterate.next();
                    if(fileType=="mav2opc")
                            {
                             String deviceName1 = entry2.get("DeviceName").toString();
                             String userName = entry2.get("UserName").toString();
                             String password = entry2.get("Password").toString();
                             String deviceType = entry2.get("DeviceType").toString();
                             String ipAddress = entry2.get("IPAddress").toString();
                             myDevice = new Device(deviceName1, userName, password, deviceType,ipAddress);
                             openJSON(deviceType,deviceName1);
                             System.out.println(myDevice);
                            } else
                            {
                                //Add a tag
                                String tagName = entry2.get("tagName").toString();
                                String tagType = entry2.get("tagType").toString();
                                String tagXPath = entry2.get("tagXPath").toString();
                                String tagWritable = entry2.get("tagWritable").toString();
                            }

                }
            } 

            //System.out.println("==toJSONString()==");
            //System.out.println(JSONValue.toJSONString(json));

      } catch (FileNotFoundException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      } catch(ParseException pe){
            System.out.println(pe);
    }
      return myDevice;
}

}

推荐答案

好的,所以你有两个文件,一个是设备列表,另一个是每个设备文件,它有设备的属性。两个文件的结构完全相同,我猜是像

Ok, so you have two files, one with list of devices and the other, per-device file, which has attributes of the device. The structures of the two files is exactly same, I am guessing something like

设备文件:

{{"DeviceName:"d1","UserName":"u1","Password":"p1","DeviceType":"t1","IPAddress":"i1"},
 {"DeviceName:"d2","UserName":"u2","Password":"p2","DeviceType":"t2","IPAddress":"ir"}}

并且每设备文件

{{"tagName:"n1","tagType":"t1","tagXPath":"X1","tagWritable":true}}

在每个设备文件中只有一个地图,虽然它在列表中。处理逻辑是打开文件,创建解析器,读取json和对于列表中的每个条目,处理地图。

In the per-device file there is only one map, though it is inside a list. The processing logic is to open the file, create the parser, read json and for each entry in the list process the map.

处理地图的逻辑是两者之间的唯一区别。请注意,现在你丢弃你从中读取的内容每个设备文件,你必须存储在 myDevice

The logic for processing the map is the only difference between the two. Note that right now you are discarding what you read from the per-device file, which you will have to store somewhere in the myDevice

中的一种方法是使用回调:c创建一个接口 MapHandler ,其方法为 process openJSON 接受此类型的参数,并为每种方法调用 process

One way to do this is using a callback: create an interface MapHandler that has a method process. openJSON takes a parameter of this type and calls process on it for each method.

可以使用 myDevice 构建设备级处理程序并设置字段。

The device-level handler can be constructed with the myDevice being processed and set the fields.

这篇关于递归方法返回存储为JSON文件的不同对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆