Java JSON只恢复一个项目

时间:2014-10-28 15:48:29

标签: java json swing

在桌面软件中,用户可以预先显示按钮并刷新数据库"。

所有信息都由在线服务提供,该服务返回JSON响应,这些响应保存到 DAT 文件中,然后使用http://www.json.org/java/index.html进行解析,以便保存到内存变量中作为字符串。 DAT 文件仅用于支持break-exception。

好的,所以我创建了一个SwingWorker类:​​

  1. 解析内存变量
  2. 中的内容
  3. 遍历元素
  4. 恢复项目
  5. 更新进度条
  6. 这是JSON代码的示例:

    {
      "key":"value",
      "data":{
        "Name1":{...},
        "Name2":{...},
        [...]
      }
    }
    

    "数据"的完整迭代element将创建一个List,我必须使用它创建一个JTable并填充GUI的主框架。但是在执行SwingWorker时,它只返回一个List,其中所有元素都是JSON的最后一项。

    这里是SwingWorker的代码:

    package com.wolfchamane.lolapi;
    
    import com.wolfchamane.logging.LoCLogger;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class LoLChampions extends SwingWorker{
    
        private static List<LoLChampion> _list;
        private static JProgressBar _status;
        private static LoCLogger _log;
        private static String _exePath;
        private static String _version;
        private static LoLDDBB _ddbb;
        //private static int _max;
    
        public List<LoLChampion> getDataTable(){
            return _list;
        }
    
        public LoLChampions(){}
        public LoLChampions(JProgressBar status){
            this();
            _status = status;
        }
        public LoLChampions(JProgressBar status, LoCLogger log){
            this(status);
            _log = log;
        }
        public LoLChampions(JProgressBar status, LoCLogger log, String path){
            this(status, log);
            _exePath = path;
        }
        public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb){
            this(status, log, path);
            _ddbb = ddbb;
        }
        public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb, String version) throws Exception{
            this(status, log, path, ddbb);
            _version = version;
        }
    
    
        @Override
        protected Object doInBackground() throws Exception {
            getChampionsInfo(_ddbb.getJSONChampions());        
            return true;
        }
    
        public void getChampionsInfo(JSONObject jsonChampions) throws Exception{
    
            String fldrImgsPath = _exePath+File.separator+"images";
            String fldrImgsChampions = fldrImgsPath+File.separator+"champions";
    
            File fldrImages = new File(fldrImgsPath);
            if (fldrImages.isDirectory() || fldrImages.mkdir()){
    
                File fldrChampions = new File(fldrImgsChampions);
                if (fldrChampions.isDirectory() || fldrChampions.mkdir()){
    
                    JSONObject data = jsonChampions.getJSONObject("data");
                    JSONArray championsNames = data.names();
    
                    int _max = championsNames.length();
                    _status.setMaximum(_max);
    
                    if (_list == null)
                        _list = new ArrayList<LoLChampion>();
    
                    int curr = _list.size();
                    for (int i = 0; i < _max; i++){
                        _status.setString("Fetching ["+(curr+1)+"/"+_max+"] champions icos");
    
                        //Champion object
                        LoLChampion champion = new LoLChampion();
    
                        //Champion name
                        String name = String.valueOf(championsNames.get(i));
                        champion.setChampionName(name);
                        //Champion data
                        JSONObject jsonChamp = data.getJSONObject(name);
    
                        //Champion roles
                        JSONArray tags = jsonChamp.getJSONArray("tags");
                        //Main role
                        String mRole = String.valueOf(tags.get(0));
                        champion.setChampionMainRole(mRole);
                        //Secondary role (if exists)
                        String sRole = "";                    
                        if (tags.length() > 1)
                            sRole = String.valueOf(tags.get(1));
                        champion.setChampionSecondRole(sRole);
    
                        //Champion ico.
                        File pf = new File(fldrChampions.getPath()+File.separator+name+".jpg");
                        saveChampionImage(name, pf);                                
                        champion.setChampionIco(pf);
    
                        //Push LoLChampion object to list
                        _list.add(champion);
    
                        //Update status bar
                        curr = _list.size();
                        _status.setValue(curr);
    
                        System.gc();
                    }//for:i
    
                    _ddbb.setChampionsList(_list);
    
                }else{
                    _log.error("Couldn't access or create \""+fldrImgsChampions+"\" folder");
                    throw new Exception("Couldn't access or create \""+fldrImgsChampions+"\" folder");
                }//fi
            }else{
                _log.error("Couldn't access or create \""+fldrImgsPath+"\" folder");
                throw new Exception("Couldn't access or create \""+fldrImgsPath+"\" folder");
            }//fi
    
        }
    
        private void saveChampionImage(String name, File pf) throws Exception{
    
            String endPointURL = (new ApiURLs()).getChampionsIcoURL();
            endPointURL = endPointURL.replace("{version}", _version);
            endPointURL = endPointURL.replace("{champion}", name);
    
            try{
    
                if (!pf.canWrite())
                    pf.createNewFile();
    
                URL url = new URL(endPointURL);
                InputStream is = url.openStream();
                OutputStream os = new FileOutputStream(pf);
    
                _log.info("Getting \""+endPointURL+"\"");
                _log.info("Saving to \""+pf.getPath()+"\"");
    
                byte[] buffer = new byte[2048];
                int length;
                while((length = is.read(buffer)) != -1){
                    os.write(buffer, 0, length);
                }//while
    
                is.close();
                os.close();
    
            }catch(Exception ex){
                _log.error(ex.getMessage());
            }
        }
    }
    

    更新

    这是我要解析的完整JSON: https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?champData=tags&api_key=d34be821-7f22-4d55-85da-7409413e6379

1 个答案:

答案 0 :(得分:1)

我不认为您的JSON示例格式正确。 JSON由名称值对组成。应该有一个&#34;:&#34;在名称和价值之间。

这样的事情:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

您提供的JSON示例看起来格格不入。有关详细信息,请参阅json.org