2016-11-07 3 views
1

Мне нужно разобрать ниже содержимое JSON. В настоящее время я сохранил файл для раздувания и чтения. Я дал образцы классов POJO, которые были созданы, и код, который я пробовал ниже.Gson для разбора строки массивов

Пробовал два разных подхода, и оба дают следующую ошибку

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $

Json файл


{ 
    "DeviceCommon": { 
     "ASIdentifier": "123", 
     "DatadeliveyMechanism": "notify", 
     "MobileOriginatorCallbackReference": { 
      "url": "http://application.example.com/inbound/notifications/modatanotification/" 
     }, 
     "AccessiblityCallbackReference": { 
      "url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification" 
     } 
    }, 
    "DeviceList": [{ 
     "ExternalIdentifer": "[email protected]", 
     "msisdn": "123456", 
     "senderName": "Device1", 
     "MobileOriginatorCallbackReference": { 
      "notifyURL": "http://application.example.com/inbound/notifications/modatanotification/" 
     }, 
     "ConfigurationResultCallbackReference": { 
      "notifyURL": "http://application.example.com/inbound/notifications/configurationResult" 
     }, 
     "ASreferenceID": "AS000001", 
     "NIDDduration": "1d" 
    }] 
} 

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+"]"; 
    } 
} 

package com.As.jsonmodel.configrequest; 


public class DeviceList 
{ 
    private MobileOriginatorCallbackReference MobileOriginatorCallbackReference; 

    private String NIDDduration; 

    private String ASreferenceID; 

    private String senderName; 

    private String ExternalIdentifer; 

    private String msisdn; 

    private ConfigurationResultCallbackReference ConfigurationResultCallbackReference; 

    public MobileOriginatorCallbackReference getMobileOriginatorCallbackReference() 
    { 
     return MobileOriginatorCallbackReference; 
    } 

    public void setMobileOriginatorCallbackReference (MobileOriginatorCallbackReference MobileOriginatorCallbackReference) 
    { 
     this.MobileOriginatorCallbackReference = MobileOriginatorCallbackReference; 
    } 

    public String getNIDDduration() 
    { 
     return NIDDduration; 
    } 

    public void setNIDDduration (String NIDDduration) 
    { 
     this.NIDDduration = NIDDduration; 
    } 

    public String getASreferenceID() 
    { 
     return ASreferenceID; 
    } 

    public void setASreferenceID (String ASreferenceID) 
    { 
     this.ASreferenceID = ASreferenceID; 
    } 

    public String getSenderName() 
    { 
     return senderName; 
    } 

    public void setSenderName (String senderName) 
    { 
     this.senderName = senderName; 
    } 

    public String getExternalIdentifer() 
    { 
     return ExternalIdentifer; 
    } 

    public void setExternalIdentifer (String ExternalIdentifer) 
    { 
     this.ExternalIdentifer = ExternalIdentifer; 
    } 

    public String getMsisdn() 
    { 
     return msisdn; 
    } 

    public void setMsisdn (String msisdn) 
    { 
     this.msisdn = msisdn; 
    } 

    public ConfigurationResultCallbackReference getConfigurationResultCallbackReference() 
    { 
     return ConfigurationResultCallbackReference; 
    } 

    public void setConfigurationResultCallbackReference (ConfigurationResultCallbackReference ConfigurationResultCallbackReference) 
    { 
     this.ConfigurationResultCallbackReference = ConfigurationResultCallbackReference; 
    } 

    @Override 
    public String toString() 
    { 
     return "ClassPojo [MobileOriginatorCallbackReference = "+MobileOriginatorCallbackReference+", NIDD duration = "+NIDDduration+", AS referenceID = "+ASreferenceID+", senderName = "+senderName+", ExternalIdentifer = "+ExternalIdentifer+", msisdn = "+msisdn+", ConfigurationResultCallbackReference = "+ConfigurationResultCallbackReference+"]"; 
    } 
} 

Json Считыватель
Approach1:

 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 

Aproach2:

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

Все рекомендации по анализу этого файла будут полезны.

+3

Вы могли бы серьезно рассмотреть вопрос об использовании только ** Http: //www.jsonschema2pojo. org/** копировать JSON, и вы буквально получаете классы, которые GSON анализирует этот файл (просто убедитесь, что вы установили его в 'JSON' в качестве входного формата и' GSON' как библиотеку) – EpicPandaForce

+0

'DeviceList [] myTypes = gson .fromJson (.../file.json) 'из того, что мы видим, ваш JSON не имеет массив, но o bject, который содержит массив. Используйте 'ConfigurationRequest cr = gson.fromJson (.../file.json)', а затем из возвращаемого объекта get array вы хотите 'cr.getDeviceList()'. – Pshemo

+0

Почему вы используете 'DeviceList []' type вместо 'ConfigurationRequest' ?? – njzk2

ответ

1

Вот как это сделать с Gson:

import java.io.FileReader; 
import java.util.Arrays; 
import com.google.gson.Gson; 
import com.google.gson.annotations.SerializedName; 

public class Main { 
    public static void main(String[] args) throws Exception { 
     Data data = new Gson().fromJson(new FileReader("data.json"), Data.class); 
     System.out.println(data); 
    } 
} 

class Data { 

    @SerializedName("DeviceCommon") 
    DeviceCommon deviceCommon; 

    @SerializedName("DeviceList") 
    DeviceListEntry[] deviceList; 

    @Override 
    public String toString() { 
     return "Data{" + 
       "\n deviceCommon=" + deviceCommon + 
       "\n deviceList=" + Arrays.toString(deviceList) + 
       "\n}"; 
    } 
} 

class DeviceCommon { 

    @SerializedName("ASIdentifier") 
    String asIdentifier; 

    @SerializedName("DatadeliveyMechanism") 
    String datadeliveyMechanism; 

    @SerializedName("MobileOriginatorCallbackReference") 
    Url mobileOriginatorCallbackReference; 

    @SerializedName("AccessiblityCallbackReference") 
    Url accessiblityCallbackReference; 

    @Override 
    public String toString() { 
     return "DeviceCommon{" + 
       "\n asIdentifier='" + asIdentifier + '\'' + 
       "\n datadeliveyMechanism='" + datadeliveyMechanism + '\'' + 
       "\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference + 
       "\n accessiblityCallbackReference=" + accessiblityCallbackReference + 
       "\n }"; 
    } 
} 

class DeviceListEntry { 

    @SerializedName("ExternalIdentifer") 
    String externalIdentifer; 

    String msisdn; 

    String senderName; 

    @SerializedName("MobileOriginatorCallbackReference") 
    NotifyUrl mobileOriginatorCallbackReference; 

    @SerializedName("ConfigurationResultCallbackReference") 
    NotifyUrl configurationResultCallbackReference; 

    @SerializedName("ASreferenceID") 
    String asReferenceID; 

    @SerializedName("NIDDduration") 
    String nidDduration; 

    @Override 
    public String toString() { 
     return "DeviceListEntry{" + 
       "\n externalIdentifer='" + externalIdentifer + '\'' + 
       "\n msisdn='" + msisdn + '\'' + 
       "\n senderName='" + senderName + '\'' + 
       "\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference + 
       "\n configurationResultCallbackReference=" + configurationResultCallbackReference + 
       "\n asReferenceID='" + asReferenceID + '\'' + 
       "\n nidDduration='" + nidDduration + '\'' + 
       "\n }"; 
    } 
} 

class Url { 

    String url; 

    @Override 
    public String toString() { 
     return url; 
    } 
} 

class NotifyUrl { 

    String notifyURL; 

    @Override 
    public String toString() { 
     return notifyURL; 
    } 
} 

Запуск Main приведет следующий вывод:

Data{ 
    deviceCommon=DeviceCommon{ 
    asIdentifier='123' 
    datadeliveyMechanism='notify' 
    mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/ 
    accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification 
    } 
    deviceList=[DeviceListEntry{ 
    externalIdentifer='[email protected]' 
    msisdn='123456' 
    senderName='Device1' 
    mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/ 
    configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult 
    asReferenceID='AS000001' 
    nidDduration='1d' 
    }] 
} 
+0

Спасибо за решение. Это очень помогло. Еще пара вопросов. 1. Как я могу получить конкретную заявку (например, misdn) из класса данных? 2. Вместо того, чтобы читать файл, как я могу получить его из http-запроса. Идея здесь заключается в том, что пользователь отправляет данные JSON на сервер REST. (Post), мне нужно прямо прочитать содержимое из HTTP и вызвать gson от Json. – ramkriz

+0

@ramkriz вы получаете определенные поля, создавая для них методы. Я рекомендую вам создавать здесь новые вопросы по SO для любых оставшихся проблем, которые у вас есть. Эти поля комментариев не очень подходят для вопросов и ответов. –

+0

ok спасибо за информацию – ramkriz

Смежные вопросы