Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从json数据创建hashmap_Java_Json_Parsing - Fatal编程技术网

Java 从json数据创建hashmap

Java 从json数据创建hashmap,java,json,parsing,Java,Json,Parsing,我正在为一个网站开发一个非常简单的应用程序,只是一个基本的桌面应用程序 因此,我已经找到了如何获取所需的所有JSON数据,如果可能的话,我正在尝试避免使用外部库来解析JSON 以下是我现在正在做的事情: package me.thegreengamerhd.TTVPortable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.ne

我正在为一个网站开发一个非常简单的应用程序,只是一个基本的桌面应用程序

因此,我已经找到了如何获取所需的所有JSON数据,如果可能的话,我正在尝试避免使用外部库来解析JSON

以下是我现在正在做的事情:

package me.thegreengamerhd.TTVPortable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import me.thegreengamerhd.TTVPortable.Utils.Messenger;


public class Channel
{
URL url;
String data;
String[] dataArray;

String name;
boolean online;
int viewers;
int followers;

public Channel(String name)
{
    this.name = name;
}

public void update() throws IOException
{
    // grab all of the JSON data from selected channel, if channel exists
    try
    {
        url = new URL("https://api.twitch.tv/kraken/channels/" + name);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        data = new String(in.readLine());
        in.close();
        // clean up data a little, into an array
        dataArray = data.split(",");
    }
    // channel does not exist, throw exception and close client
    catch (Exception e)
    {
        Messenger.sendErrorMessage("The channel you have specified is invalid or corrupted.", true);
        e.printStackTrace();
        return;
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < dataArray.length; i++)
    {
        sb.append(dataArray[i] + "\n");
    }

    System.out.println(sb.toString());
}
}
正在初始化用户界面-加入

所有这些都是正确的。现在我想做的是,能够抓取,比如“成熟”标签,以及它的价值。因此,当我抓住它时,它会像以下一样简单:

// pseudo code
if(mature /*this is a boolean */ == true){ // do stuff}

因此,如果您不理解,我需要将值之间的引号和分号分开,以检索键Value。

这是一个简单json字符串的解析器:

public static HashMap<String, String> parseEasyJson(String json) {
    final String regex = "([^{}: ]*?):(\\{.*?\\}|\".*?\"|[^:{}\" ]*)";
    json = json.replaceAll("\n", "");
    Matcher m = Pattern.compile(regex).matcher(json);
    HashMap<String, String> map = new HashMap<>();
    while (m.find())
        map.put(m.group(1), m.group(2));
    return map;
}
公共静态HashMap parseEasyJson(字符串json){
最后一个字符串regex=“([^{}::*?):(\\{.*?\}\\\\\\\\\\\\\\\\\\\\\\\\\”*?“\\\\[^:{}\']*)”;
json=json.replaceAll(“\n”和“”);
Matcher m=Pattern.compile(regex.Matcher)(json);
HashMap=newHashMap();
while(m.find())
map.put(m.group(1)、m.group(2));
返回图;
}

通过以下代码可以实现:

public static Map<String, Object> parseJSON (String data) throws ParseException {
    if (data==null)
        return null;
    final Map<String, Object> ret = new HashMap<String, Object>();
    data = data.trim();
    if (!data.startsWith("{") || !data.endsWith("}"))
        throw new ParseException("Missing '{' or '}'.", 0);

    data = data.substring(1, data.length()-1);

    final String [] lines = data.split("[\r\n]");

    for (int i=0; i<lines.length; i++) {
        String line = lines[i];

        if (line.isEmpty())
            continue;

        line = line.trim();

        if (line.indexOf(":")<0)
            throw new ParseException("Missing ':'.", 0);

        String key = line.substring(0, line.indexOf(":"));
        String value = line.substring(line.indexOf(":")+1);

        if (key.startsWith("\"") && key.endsWith("\"") && key.length()>2)
            key = key.substring(1, key.length()-1);

        if (value.startsWith("{"))
            while (i+1<line.length() && !value.endsWith("}"))
                value = value + "\n" + lines[++i].trim();

        if (value.startsWith("\"") && value.endsWith("\"") && value.length()>2)
            value = value.substring(1, value.length()-1);

        Object mapValue = value;

        if (value.startsWith("{") && value.endsWith("}"))
            mapValue = parseJSON(value);
        else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))
            mapValue = new Boolean (value);
        else {
            try {
                mapValue = Integer.parseInt(value);
            } catch (NumberFormatException nfe) {
                try {
                    mapValue = Long.parseLong(value);
                } catch (NumberFormatException nfe2) {}
            }
        }

        ret.put(key, mapValue);
    }

    return ret;
}
publicstaticmap-parseJSON(字符串数据)抛出ParseException{
如果(数据==null)
返回null;
final Map ret=新的HashMap();
data=data.trim();
如果(!data.startsWith(“{”)| |!data.endsWith(“}”))
抛出新的ParseException(“缺少“{”或“}.”,0);
data=data.substring(1,data.length()-1);
最终字符串[]行=data.split([\r\n]”);

对于(int i=0;iYou可以用大约500行代码编写一个基本的JSON解析器。请动手吧!(但是当Java可能有十几个好的开源JSON解析器可用时,其他人会质疑您的理智。)啊,我想使用json.org/java上的那个,但我不知道如何将它添加到我的eclipse库中……你可以随时问这个问题。谢谢!只是好奇,当它包含引号时,我如何才能抓取键?编辑:我似乎无法抓取任何键或值。你能提供一个例子吗?@MichaelGates try
final String regex=“\”(.*?\:(\{.*?\}.*?\[^:{}\']*)”;
谢谢,但我自己解决了!不过谢谢你!
public static Map<String, Object> parseJSON (String data) throws ParseException {
    if (data==null)
        return null;
    final Map<String, Object> ret = new HashMap<String, Object>();
    data = data.trim();
    if (!data.startsWith("{") || !data.endsWith("}"))
        throw new ParseException("Missing '{' or '}'.", 0);

    data = data.substring(1, data.length()-1);

    final String [] lines = data.split("[\r\n]");

    for (int i=0; i<lines.length; i++) {
        String line = lines[i];

        if (line.isEmpty())
            continue;

        line = line.trim();

        if (line.indexOf(":")<0)
            throw new ParseException("Missing ':'.", 0);

        String key = line.substring(0, line.indexOf(":"));
        String value = line.substring(line.indexOf(":")+1);

        if (key.startsWith("\"") && key.endsWith("\"") && key.length()>2)
            key = key.substring(1, key.length()-1);

        if (value.startsWith("{"))
            while (i+1<line.length() && !value.endsWith("}"))
                value = value + "\n" + lines[++i].trim();

        if (value.startsWith("\"") && value.endsWith("\"") && value.length()>2)
            value = value.substring(1, value.length()-1);

        Object mapValue = value;

        if (value.startsWith("{") && value.endsWith("}"))
            mapValue = parseJSON(value);
        else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))
            mapValue = new Boolean (value);
        else {
            try {
                mapValue = Integer.parseInt(value);
            } catch (NumberFormatException nfe) {
                try {
                    mapValue = Long.parseLong(value);
                } catch (NumberFormatException nfe2) {}
            }
        }

        ret.put(key, mapValue);
    }

    return ret;
}
try {
    Map<String, Object> ret = parseJSON(sb.toString());
    if(((Boolean)ret.get("mature")) == true){
        System.out.println("mature is true !");
    }
} catch (ParseException e) {

}