Java Gson解析数组字符串

Java Gson解析数组字符串,java,json,gson,Java,Json,Gson,我需要解析下面的JSON内容。目前我已将其存储在充气文件中并进行读取。我已经给出了创建的示例POJO类和我在下面尝试的代码 尝试了两种不同的方法,但都出现以下错误 线程“main”com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为BEGIN_数组,但在第1行第3列路径$处为BEGIN_对象 Json文件 POJO课程: 注意:我在这里只提到了两个类 package com.As.jsonmodel.con

我需要解析下面的JSON内容。目前我已将其存储在充气文件中并进行读取。我已经给出了创建的示例POJO类和我在下面尝试的代码

尝试了两种不同的方法,但都出现以下错误

线程“main”com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为BEGIN_数组,但在第1行第3列路径$处为BEGIN_对象

Json文件


POJO课程:
注意:我在这里只提到了两个类

package com.As.jsonmodel.configrequest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)

public class ConfigurationRequest
{
    private DeviceList[] DeviceList;

    private DeviceCommon DeviceCommon;

    public DeviceList[] getDeviceList ()
    {
        return DeviceList;
    }

    public void setDeviceList (DeviceList[] DeviceList)
    {
        this.DeviceList = DeviceList;
    }

    public DeviceCommon getDeviceCommon ()
    {
        return DeviceCommon;
    }

    public void setDeviceCommon (DeviceCommon DeviceCommon)
    {
        this.DeviceCommon = DeviceCommon;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [DeviceList = "+DeviceList+", DeviceCommon = "+DeviceCommon+"]";
    }
}


Json阅读器
方法1:

        BufferedReader br = null;
        try {
            br = new BufferedReader(  
                     new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        JsonReader jsonReader = new JsonReader(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));

        jsonReader.beginObject();

        while (jsonReader.hasNext()) {

        String name = jsonReader.nextName();
            if (name.equals("DeviceCommon")) {
                 readApp(jsonReader);

            }
        }

        jsonReader.endObject();
        jsonReader.close();
    }

    public static void readApp(JsonReader jsonReader) throws IOException{
        jsonReader.beginObject();
         while (jsonReader.hasNext()) {
             String name = jsonReader.nextName();
             System.out.println(name);
             if (name.contains("ASIdentifier")){
                 jsonReader.beginObject();
                 while (jsonReader.hasNext()) {
                     String n = jsonReader.nextName();
                     if (n.equals("MobileOriginatorCallbackReference")){
                         System.out.println(jsonReader.nextString());
                     }
                     if (n.equals("AccessiblityCallbackReference")){
                         System.out.println(jsonReader.nextInt());
                     }
                     if (n.equals("DeviceList")){
                         jsonReader.beginArray();
                         while  (jsonReader.hasNext()) {
                              System.out.println(jsonReader.nextString());
                         }
                         jsonReader.endArray();
                     }
                 }
                 jsonReader.endObject();
             }

         }
         jsonReader.endObject();
    }


    // TODO Auto-generated method stub
第2条:

Gson gson = new Gson();
DeviceList [] myTypes = gson.fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), DeviceList[].class);
System.out.println(gson.toJson(myTypes));

任何有关如何解析此文件的指针都会很有帮助。

以下是如何使用Gson进行解析:

导入java.io.FileReader;
导入java.util.array;
导入com.google.gson.gson;
导入com.google.gson.annotations.SerializedName;
公共班机{
公共静态void main(字符串[]args)引发异常{
Data Data=new Gson().fromJson(新文件读取器(“Data.json”)、Data.class);
系统输出打印项次(数据);
}
}
类数据{
@SerializedName(“DeviceCommon”)
DeviceCommon DeviceCommon;
@序列化名称(“设备列表”)
设备列表[]设备列表;
@凌驾
公共字符串toString(){
返回“数据{”+
“\n deviceCommon=“+deviceCommon”+
“\n deviceList=“+Arrays.toString(deviceList)+
“\n}”;
}
}
类DeviceCommon{
@序列化名称(“身份识别器”)
字符串识别器;
@SerializedName(“DataDeliveryMechanism”)
字符串数据传递机制;
@SerializedName(“MobileOrginatorCallbackReference”)
Url mobileOriginatorCallbackReference;
@SerializedName(“AccessiblityCallbackReference”)
Url可访问CallbackReference;
@凌驾
公共字符串toString(){
返回“DeviceCommon{”+
“\n asIdentifier='”+asIdentifier+'\''+
“\n DataDeliveryMechanism='”+DataDeliveryMechanism+'\''+
“\n MobileOrginatorCallbackReference=“+MobileOrginatorCallbackReference+
“\n accessiblityCallbackReference=“+accessiblityCallbackReference+
“\n}”;
}
}
类设备登录{
@SerializedName(“外部标识符”)
字符串外部标识符;
字符串msisdn;
字符串发送器名称;
@SerializedName(“MobileOrginatorCallbackReference”)
NotifyUrl mobileOriginatorCallbackReference;
@SerializedName(“ConfigurationResultCallbackReference”)
NotifyUrl配置ResultCallbackReference;
@SerializedName(“ASreferenceID”)
字符串asReferenceID;
@SerializedName(“NIDDduration”)
字符串nidDduration;
@凌驾
公共字符串toString(){
返回“DeviceListEntry{”+
“\n externalIdentifier='”+externalIdentifier+'\''+
“\n msisdn='”+msisdn+'\''+
“\n senderName=”+senderName+“\”+
“\n MobileOrginatorCallbackReference=“+MobileOrginatorCallbackReference+
“\n configurationResultCallbackReference=“+configurationResultCallbackReference+
“\n asReferenceID=”+asReferenceID+“\”+
“\n nidDduration=”+nidDduration+'\''+
“\n}”;
}
}
类Url{
字符串url;
@凌驾
公共字符串toString(){
返回url;
}
}
类NotifyUrl{
字符串通知URL;
@凌驾
公共字符串toString(){
返回notifyURL;
}
}
运行
Main
将产生以下输出:

数据{
deviceCommon=deviceCommon{
asIdentifier='123'
DataDeliveryMechanism='notify'
MobileOrginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
可访问性CallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry]{
外部识别器123456@mydomain.com'
msisdn='123456'
senderName='Device1'
MobileOrginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}

您可以认真考虑使用JSON IN,并且从字面上获得GSON解析这个文件的类(只需确保将其设置为<代码> JSON < /代码>作为输入格式,而<代码> GSON<代码>为库)<代码> DeCielist[] MyType=GSON.FROJSON(…/file .jSON)< /Cord> >从我们看到的JSON不持有数组,但包含数组的对象。使用
ConfigurationRequest cr=gson.fromJson(…/file.json)
,然后从返回的对象获取所需的数组
cr.getDeviceList()
。为什么要使用
DeviceList[]
类型而不是
ConfigurationRequest
?感谢您的解决方案。这很有帮助。还有几个问题。1.如何从数据类获取特定的字段(例如misdn)?2.我如何从http请求中获取它,而不是读取它的文件。这里的想法是用户将这个JSON数据发送到REST服务器。(post)方法,我需要直接从HTTP读取内容并从JSON调用gson。@ramkriz您可以通过为它们创建方法来获得特定字段。我建议您在此处创建新问题,以便解决任何遗留问题。这些评论框并不适合问答。
        BufferedReader br = null;
        try {
            br = new BufferedReader(  
                     new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        JsonReader jsonReader = new JsonReader(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));

        jsonReader.beginObject();

        while (jsonReader.hasNext()) {

        String name = jsonReader.nextName();
            if (name.equals("DeviceCommon")) {
                 readApp(jsonReader);

            }
        }

        jsonReader.endObject();
        jsonReader.close();
    }

    public static void readApp(JsonReader jsonReader) throws IOException{
        jsonReader.beginObject();
         while (jsonReader.hasNext()) {
             String name = jsonReader.nextName();
             System.out.println(name);
             if (name.contains("ASIdentifier")){
                 jsonReader.beginObject();
                 while (jsonReader.hasNext()) {
                     String n = jsonReader.nextName();
                     if (n.equals("MobileOriginatorCallbackReference")){
                         System.out.println(jsonReader.nextString());
                     }
                     if (n.equals("AccessiblityCallbackReference")){
                         System.out.println(jsonReader.nextInt());
                     }
                     if (n.equals("DeviceList")){
                         jsonReader.beginArray();
                         while  (jsonReader.hasNext()) {
                              System.out.println(jsonReader.nextString());
                         }
                         jsonReader.endArray();
                     }
                 }
                 jsonReader.endObject();
             }

         }
         jsonReader.endObject();
    }


    // TODO Auto-generated method stub
Gson gson = new Gson();
DeviceList [] myTypes = gson.fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), DeviceList[].class);
System.out.println(gson.toJson(myTypes));