使用Gson进行示例语法检查(使用lombok):
package com.stackoverflow.so13701022;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
public class CheckJson {
@Data
private static class LineOfBusiness {
@SerializedName("LOB1")
private String lob1;
@SerializedName("LOB2")
private String lob2;
@SerializedName("LOB3")
private String lob3;
@SerializedName("LOB4")
private String lob4;
}
@Data
private static class Market {
@SerializedName("MKTID001")
private String mktid001;
@SerializedName("MKTID002")
private String mktid002;
@SerializedName("LOB3")
private String lob3;
@SerializedName("LOB4")
private String lob4;
}
private static final String ONE = "{" +
" LOB1 : \"LOBAppType=sadfsd\"," +
" LOB2 : \"LOBAppType=asdf\"," +
" LOB3 : \"LOBAppType=asdf}" +
" LOB4 : \"LOBAppType=sdf\"," +
"}";
// I corrected this one on purpose
private static final String TWO = "{" +
" MKTID001 :\"MarketName=US||Descr=USA\"," +
" MKTID002 :\"MarketName=JP||Descr=Japan\"," +
" LOB3 : \"LOBAppType=asdf\"," +
" LOB4 : \"LOBAppType=sdf\"" +
"}";
public static void main(String[] args)
{
final Gson gson = new GsonBuilder().create();
System.out.println(tryParse(gson, ONE, LineOfBusiness.class));
System.out.println(tryParse(gson, TWO, Market.class));
}
private static <T> T tryParse(Gson gson, String what, Class<T> clazz)
{
try {
return gson.fromJson(what, clazz);
} catch (final JsonSyntaxException e) {
System.err.println(e);
}
return null;
}
}
输出(错误 = 标准错误,输出 = 标准输出):
(Err) com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 159
(Out) null
(Out) CheckJson.Market(mktid001=MarketName=US||Descr=USA, mktid002=MarketName=JP||Descr=Japan, lob3=LOBAppType=asdf, lob4=LOBAppType=sdf)