如何解析用方括号编码的json数据

时间:2014-02-01 23:24:30

标签: java grails

我正在使用mailgun,webhook使用以下格式的json数据向我的服务器发送帖子。我不熟悉如何解析这种不使用大括号的json请求。我不确定调用哪种格式来搜索解决方案。

我需要解析返回字符串并能够以json ['Received']

的形式访问元素
[["Received", "by luna.mailgun.net with SMTP mgrt 8778766572977; Sat, 01 Feb 2014 22:55:12 +0000"
 ["X-Envelope-From", "<person@domain.com>"
 ["Return-Path", "<person@domain.com>"
 ["Received", "from some data here Sat, 01 Feb 2014 14:55:09 -0800 (PST)"
 ["Content-Type", "text/plain; charset=\"us-ascii\""
 ["Mime-Version", "1.0 (Mac OS X Mail 6.6 \\(1510\\))"
 ["Subject", "Re: Hello world"
 ["From", "AT <you@you.com>"
 ["In-Reply-To", "<20140201225343.7954.82391@mydomain.com>"
 ["Date", "Sat, 1 Feb 2014 16:55:08 -0600"
 ["Content-Transfer-Encoding", "7bit"
 ["Message-Id", "<86C3EA0C-5D9B-4BFA-A76B-54CFC3238714@you.com>"
 ["References", "<20140201225343.7954.82391@mydomain.com>"
 ["To", "messages@mydomain.com"
 ["X-Mailgun-Incoming", "Yes"]]

1 个答案:

答案 0 :(得分:1)

这确实不是JSON。

你可以解析它,例如像这样。

如果您将此文件保存为UTF-8,请确保将其保存为
没有BOM,否则下面这个程序将产生额外的 第一行看起来像空,但不是。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

class Test {

    public static void main(String[] args) throws Exception{
        String fn = "C:\\Various\\input.txt";
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fn), "UTF8"));
        StringBuilder sb = new StringBuilder();
        String str = null;
        while ((str = br.readLine())!=null){
            sb.append(str);
        }
        br.close();
        String z = sb.toString();
        String[] arr = z.split("\\[+|\\]+|, \"");
        for (int i=0; i<arr.length; i++){
            arr[i] = arr[i].trim();
            if (!arr[i].isEmpty()){
                if (arr[i].charAt(0) == '"'){
                    arr[i] = arr[i].substring(1);
                }
                if (arr[i].charAt(arr[i].length() - 1) == '"'){
                    arr[i] = arr[i].substring(0, arr[i].length() - 1);
                }
                System.out.println(arr[i]);
            }
        }
    }

}