从json数据创建hashmap

时间:2013-05-25 02:57:42

标签: java json parsing

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

所以我想出了如何获取我需要的所有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());
}
}

所以这是我输入示例频道(正确抓取数据)时打印的内容

    {"updated_at":"2013-05-24T11:00:26Z"
"created_at":"2011-06-28T07:50:25Z"
"status":"HD [XBOX] Call of Duty Black Ops 2 OPEN LOBBY"
"url":"http://www.twitch.tv/zetaspartan21"
"_id":23170407
"game":"Call of Duty: Black Ops II"
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-profile_image-121d2cb317e8a91c-300x300.jpeg"
"banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_header_image-7c894f59f77ae0c1-640x125.png"
"_links":{"subscriptions":"https://api.twitch.tv/kraken/channels/zetaspartan21/subscriptions"
"editors":"https://api.twitch.tv/kraken/channels/zetaspartan21/editors"
"commercial":"https://api.twitch.tv/kraken/channels/zetaspartan21/commercial"
"teams":"https://api.twitch.tv/kraken/channels/zetaspartan21/teams"
"features":"https://api.twitch.tv/kraken/channels/zetaspartan21/features"
"videos":"https://api.twitch.tv/kraken/channels/zetaspartan21/videos"
"self":"https://api.twitch.tv/kraken/channels/zetaspartan21"
"follows":"https://api.twitch.tv/kraken/channels/zetaspartan21/follows"
"chat":"https://api.twitch.tv/kraken/chat/zetaspartan21"
"stream_key":"https://api.twitch.tv/kraken/channels/zetaspartan21/stream_key"}
"name":"zetaspartan21"
"delay":0
"display_name":"ZetaSpartan21"
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_offline_image-b20322d22543539a-640x360.jpeg"
"background":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_background_image-587bde3d4f90b293.jpeg"
"mature":true}

初始化用户界面 - 加入

所有这一切都是正确的。现在我想做的是,能够抓住,例如'成熟'标签,它的价值。因此,当我抓住它时,它就像:

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

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

2 个答案:

答案 0 :(得分:1)

可以使用以下代码:

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) {

}

但是,实际上,你不应该这样做,并且使用已经存在的JSON解析器,因为这段代码会破坏任何复杂或无效的JSON数据(比如&#34; :&#34;在键中),如果你想手工构建一个真正的JSON解析器,它将需要你更多的代码和调试!

答案 1 :(得分:0)

这是一个简单的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;
}

Live Demo