Разбор Json с использованием Джексона или Gson

Как проанализировать одинаковые ключи объекта json для двух разных классов моделей, используя jackson или же Gson?

Это вход json

 {
      "last_sync_dt": "1486711867749",
      "meetings_info": [
        {
          "date": "2017-01-15",
          "meeting_id": "1",
          "subject": "Product Review with AUDI",
          "customer_id": "32",
          "customer_name": "David"
        }
      ]
    }  

Это модельный класс

@JsonIgnoreProperties(ignoreUnknown = true)
Class MeetingInfo{
    @JsonProperty("date")
    private String date;
    @JsonProperty("meeting_id")
    private String meetingId;
    @JsonProperty("subject")
    private String subject;

    CustomerInfo customerinfo; 


//Other fields and getter setter


}

class CustomerInfo{
    @JsonProperty("customer_id")
    private String id;
   @JsonProperty("customer_name")
    private String name;

//Other fields and getter setter
}

4 ответа

Решение

Пожалуйста, добавьте объект для глобального объекта

Class ResultJson{
  String last_sync_dt;
  ArrayList<MeetingInfo> meetings_info;
}

и MeetingInfo будет

public class MeetingInfo {
    private String date;
    private String meeting_id;
    private String subject;
    private CustomerInfo customerInfo;

    public void setDate(String date) {
        this.date = date;
    }

    public void setMeeting_id(String meeting_id) {
        this.meeting_id = meeting_id;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setCustomer(CustomerInfo customer) {
        customerInfo = customer;
    }
}

Информация о клиенте

public class CustomerInfo {
    private String customer_id;
    private String customer_name;

    public void setCustomerId(String customer_id) {
        this.customer_id = customer_id;
    }

    public void setCustomerName(String customer_name) {
        this.customer_name = customer_name;
    }
}

Встреча десериализатора

public class MeetingInfoAutho implements JsonDeserializer<MeetingInfo>{

    @Override
    public MeetingInfo deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jObject = jsonElement.getAsJsonObject();
        MeetingInfo info = new MeetingInfo();
        CustomerInfo customer = new CustomerInfo();
        customer.setCustomerId(jObject.get("customer_id").getAsString());
        customer.setCustomerName(jObject.get("customer_name").getAsString());
        info.setDate(jObject.get("date").getAsString());
        info.setMeeting_id(jObject.get("meeting_id").getAsString());
        info.setSubject(jObject.get("subject").getAsString());
        info.setCustomer(customer);
        Log.e("info", jObject.toString());
        return info;
    }
}

и последний вызов строки JSON для объекта

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MeetingInfo.class, new MeetingInfoAutho());
Gson gson = gsonBuilder.create();
ResultJson resultObject = gson.fromJson(jsonStr, ResultJson.class);

Вы должны создать MeetingInfoAutho, который реализует JsonDeserializer. Пожалуйста, найдите несколько примеров о JsonDeserializer GSON для получения дополнительной информации.Это даст точный результат.

Вот пример из вашего кода с использованием gson.

@JsonIgnoreProperties(ignoreUnknown = true)
Class RootClass {
    @JsonProperty("last_sync_dt")
    private String date;
    @JsonProperty("meetings_info")
    ArrayList<MeetingInfo> meetingInfo;
    // as you are having json array of meeting info in root 


//Other fields and getter setter


}

и в вашем MeetingInfo учебный класс

class MeetingInfo{
    @JsonProperty("date")
    private String date;
   @JsonProperty("meeting_id")
    private String meetingId;
   @JsonProperty("subject")
    private String subject;
   @JsonProperty("customer_name")
    private String cName;
   @JsonProperty("customer_id")
    private String cId;

//Other fields and getter setter
} 

и, наконец, где вы получаете ответ JSON.

Type type = new TypeToken<RootClass>() {}.getType();
RootClass rootClass = ServerController.gson.fromJson(responseObject.toString(), type);

Вы можете использовать эту ссылку для анализа JSON с помощью Джексона или Gson. он создаст ваш класс автоматически. Просто вставьте туда свой JSON.

Ссылка: http://www.jsonschema2pojo.org/

Здесь лучший способ сделать это, вы можете сгенерировать класс модели для Gson или Jackson из следующего URL, а затем после того, как вы можете установить данные Json непосредственно в классе модели, используя библиотеку Gson или Jackson.

Ссылка для создания модели: http://www.jsonschema2pojo.org/

Вот я модель Genrating для вашего ответа.

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("last_sync_dt")
@Expose
private String lastSyncDt;
@SerializedName("meetings_info")
@Expose
private List<MeetingsInfo> meetingsInfo = null;

public String getLastSyncDt() {
return lastSyncDt;
}

public void setLastSyncDt(String lastSyncDt) {
this.lastSyncDt = lastSyncDt;
}

public List<MeetingsInfo> getMeetingsInfo() {
return meetingsInfo;
}

public void setMeetingsInfo(List<MeetingsInfo> meetingsInfo) {
this.meetingsInfo = meetingsInfo;
}

}
/*-----------------------------------com.example.MeetingsInfo.java-----------------------------------*/

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MeetingsInfo {

@SerializedName("date")
@Expose
private String date;
@SerializedName("meeting_id")
@Expose
private String meetingId;
@SerializedName("subject")
@Expose
private String subject;
@SerializedName("customer_id")
@Expose
private String customerId;
@SerializedName("customer_name")
@Expose
private String customerName;

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getMeetingId() {
return meetingId;
}

public void setMeetingId(String meetingId) {
this.meetingId = meetingId;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getCustomerId() {
return customerId;
}

public void setCustomerId(String customerId) {
this.customerId = customerId;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

}

Теперь после этого вы можете напрямую установить свои данные в классе модели, как Беллоу

Example example = new Gson().fromJson(jsonRespons, new TypeToken<Example>() {
                    }.getType());
Другие вопросы по тегам