当前位置: 首页 > 知识库问答 >
问题:

POJO类上的new Gson(). toJson()返回空{}

须鸿祯
2023-03-14

这是我的代码:

private List<SearchableAddress> convertAddressToSearchableAddress(final List<Address> addressList) {
       
        final List<SearchableAddress> toReturn = new ArrayList<SearchableAddress>();
        for (final Address address : addressList) {
           App.log(TAG,"Inside convertAddressToSearchableAddress---Address---->1111 "+address); // This one is printing the address
          //Address[addressLines=[0:"Ohio, USA"],feature=Ohio,admin=Ohio,sub-admin=null,locality=null,thoroughfare=null,postalCode=null,countryCode=US,countryName=United States,hasLatitude=true,latitude=40.417287099999996,hasLongitude=true,longitude=-82.90712300000001,phone=null,url=null,extras=null]

           Log.e("TTAG2",""+new Gson().toJson(searchableAddress)); //This one returns --> {"address":{}}

            // Then I've also tried this:
            SearchableAddress searchableAddress=new SearchableAddress(address);
            Gson gson = new GsonBuilder().serializeNulls().create();
            String json = gson.toJson(searchableAddress);

            App.log(TAG,"Finally we have address--->"+json); //This one is returning-->{"address":{},"fullAddress":null}

            Log.e("TTAG2",""+gson.toJson(searchableAddress)); //Being the same as above, this one is returning----

            toReturn.add(new SearchableAddress(address));
        }
        return toReturn;
    }

以下是我的ModelClass:

public class SearchableAddress {
    private static final String TAG = SearchableAddress.class.getSimpleName();
    private Address address;
    private String fullAddress;

    public SearchableAddress(final Address address){
        this.address = address;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        SearchableAddress that = (SearchableAddress) o;

        if (address.getLatitude() != that.address.getLatitude()) return false;
        if (address.getLongitude() != that.address.getLongitude()) return false;
        return true;
    }

    @Override
    public int hashCode() {
        int result = address.hashCode();
        result = 31 * result + getAddress().hashCode();
        return result;
    }

    private String convertAddressToFullAddress(final Address address) {
        boolean notComplete = true;
        int index = 0;
        String toReturn = "";
        while (notComplete) {
            final String addressLine = address.getAddressLine(index);
            if (addressLine == null) {
                notComplete = false;
                break;
            }
            toReturn = toReturn + addressLine + " ";
            index = index + 1;
        }
        return toReturn;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {

        this.address = address;

    }

    public String getFullAddress() {
        if(fullAddress == null){
            fullAddress = convertAddressToFullAddress(address);
        }
        return fullAddress;
    }

    public void setFullAddress(String fullAddress) {
        this.fullAddress = fullAddress;
    }
}

地址.java

 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.location;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;

/**
 * A class representing an Address, i.e, a set of Strings describing a location.
 *
 * The address format is a simplified version of xAL (eXtensible Address Language)
 * http://www.oasis-open.org/committees/ciq/ciq.html#6
 */
public class Address implements Parcelable {

    private Locale mLocale;

    private String mFeatureName;
    private HashMap<Integer, String> mAddressLines;
    private int mMaxAddressLineIndex = -1;
    private String mAdminArea;
    private String mSubAdminArea;
    private String mLocality;
    private String mSubLocality;
    private String mThoroughfare;
    private String mSubThoroughfare;
    private String mPremises;
    private String mPostalCode;
    private String mCountryCode;
    private String mCountryName;
    private double mLatitude;
    private double mLongitude;
    private boolean mHasLatitude = false;
    private boolean mHasLongitude = false;
    private String mPhone;
    private String mUrl;
    private Bundle mExtras = null;

    /**
     * Constructs a new Address object set to the given Locale and with all
     * other fields initialized to null or false.
     */
    public Address(Locale locale) {
        mLocale = locale;
    }

    /**
     * Returns the Locale associated with this address.
     */
    public Locale getLocale() {
        return mLocale;
    }

    /**
     * Returns the largest index currently in use to specify an address line.
     * If no address lines are specified, -1 is returned.
     */
    public int getMaxAddressLineIndex() {
        return mMaxAddressLineIndex;
    }

    /**
     * Returns a line of the address numbered by the given index
     * (starting at 0), or null if no such line is present.
     *
     * @throws IllegalArgumentException if index < 0
     */
    public String getAddressLine(int index) {
        if (index < 0) {
            throw new IllegalArgumentException("index = " + index + " < 0");
        }
        return mAddressLines == null? null :  mAddressLines.get(index);
    }

    /**
     * Sets the line of the address numbered by index (starting at 0) to the
     * given String, which may be null.
     *
     * @throws IllegalArgumentException if index < 0
     */
    public void setAddressLine(int index, String line) {
        if (index < 0) {
            throw new IllegalArgumentException("index = " + index + " < 0");
        }
        if (mAddressLines == null) {
            mAddressLines = new HashMap<Integer, String>();
        }
        mAddressLines.put(index, line);

        if (line == null) {
            // We've eliminated a line, recompute the max index
            mMaxAddressLineIndex = -1;
            for (Integer i : mAddressLines.keySet()) {
                mMaxAddressLineIndex = Math.max(mMaxAddressLineIndex, i);
            }
        } else {
            mMaxAddressLineIndex = Math.max(mMaxAddressLineIndex, index);
        }
    }

    /**
     * Returns the feature name of the address, for example, "Golden Gate Bridge", or null
     * if it is unknown
     */
    public String getFeatureName() {
        return mFeatureName;
    }

    /**
     * Sets the feature name of the address to the given String, which may be null
     */
    public void setFeatureName(String featureName) {
        mFeatureName = featureName;
    }

    /**
     * Returns the administrative area name of the address, for example, "CA", or null if
     * it is unknown
     */
    public String getAdminArea() {
        return mAdminArea;
    }

    /**
     * Sets the administrative area name of the address to the given String, which may be null
     */
    public void setAdminArea(String adminArea) {
        this.mAdminArea = adminArea;
    }

    /**
     * Returns the sub-administrative area name of the address, for example, "Santa Clara County",
     * or null if it is unknown
     */
    public String getSubAdminArea() {
        return mSubAdminArea;
    }

    /**
     * Sets the sub-administrative area name of the address to the given String, which may be null
     */
    public void setSubAdminArea(String subAdminArea) {
        this.mSubAdminArea = subAdminArea;
    }

    /**
     * Returns the locality of the address, for example "Mountain View", or null if it is unknown.
     */
    public String getLocality() {
        return mLocality;
    }

    /**
     * Sets the locality of the address to the given String, which may be null.
     */
    public void setLocality(String locality) {
        mLocality = locality;
    }

    /**
     * Returns the sub-locality of the address, or null if it is unknown.
     * For example, this may correspond to the neighborhood of the locality.
     */
    public String getSubLocality() {
        return mSubLocality;
    }

    /**
     * Sets the sub-locality of the address to the given String, which may be null.
     */
    public void setSubLocality(String sublocality) {
        mSubLocality = sublocality;
    }

    /**
     * Returns the thoroughfare name of the address, for example, "1600 Ampitheater Parkway",
     * which may be null
     */
    public String getThoroughfare() {
        return mThoroughfare;
    }

    /**
     * Sets the thoroughfare name of the address, which may be null.
     */
    public void setThoroughfare(String thoroughfare) {
        this.mThoroughfare = thoroughfare;
    }

    /**
     * Returns the sub-thoroughfare name of the address, which may be null.
     * This may correspond to the street number of the address.
     */
    public String getSubThoroughfare() {
        return mSubThoroughfare;
    }

    /**
     * Sets the sub-thoroughfare name of the address, which may be null.
     */
    public void setSubThoroughfare(String subthoroughfare) {
        this.mSubThoroughfare = subthoroughfare;
    }

    /**
     * Returns the premises of the address, or null if it is unknown.
     */
    public String getPremises() {
        return mPremises;
    }

    /**
     * Sets the premises of the address to the given String, which may be null.
     */
    public void setPremises(String premises) {
        mPremises = premises;
    }

    /**
     * Returns the postal code of the address, for example "94110",
     * or null if it is unknown.
     */
    public String getPostalCode() {
        return mPostalCode;
    }

    /**
     * Sets the postal code of the address to the given String, which may
     * be null.
     */
    public void setPostalCode(String postalCode) {
        mPostalCode = postalCode;
    }

    /**
     * Returns the country code of the address, for example "US",
     * or null if it is unknown.
     */
    public String getCountryCode() {
        return mCountryCode;
    }

    /**
     * Sets the country code of the address to the given String, which may
     * be null.
     */
    public void setCountryCode(String countryCode) {
        mCountryCode = countryCode;
    }

    /**
     * Returns the localized country name of the address, for example "Iceland",
     * or null if it is unknown.
     */
    public String getCountryName() {
        return mCountryName;
    }

    /**
     * Sets the country name of the address to the given String, which may
     * be null.
     */
    public void setCountryName(String countryName) {
        mCountryName = countryName;
    }

    /**
     * Returns true if a latitude has been assigned to this Address,
     * false otherwise.
     */
    public boolean hasLatitude() {
        return mHasLatitude;
    }

    /**
     * Returns the latitude of the address if known.
     *
     * @throws IllegalStateException if this Address has not been assigned
     * a latitude.
     */
    public double getLatitude() {
        if (mHasLatitude) {
            return mLatitude;
        } else {
            throw new IllegalStateException();
        }
    }

    /**
     * Sets the latitude associated with this address.
     */
    public void setLatitude(double latitude) {
        mLatitude = latitude;
        mHasLatitude = true;
    }

    /**
     * Removes any latitude associated with this address.
     */
    public void clearLatitude() {
        mHasLatitude = false;
    }

    /**
     * Returns true if a longitude has been assigned to this Address,
     * false otherwise.
     */
    public boolean hasLongitude() {
        return mHasLongitude;
    }

    /**
     * Returns the longitude of the address if known.
     *
     * @throws IllegalStateException if this Address has not been assigned
     * a longitude.
     */
    public double getLongitude() {
        if (mHasLongitude) {
            return mLongitude;
        } else {
            throw new IllegalStateException();
        }
    }

    /**
     * Sets the longitude associated with this address.
     */
    public void setLongitude(double longitude) {
        mLongitude = longitude;
        mHasLongitude = true;
    }

    /**
     * Removes any longitude associated with this address.
     */
    public void clearLongitude() {
        mHasLongitude = false;
    }

    /**
     * Returns the phone number of the address if known,
     * or null if it is unknown.
     *
     * @throws IllegalStateException if this Address has not been assigned
     * a phone number.
     */
    public String getPhone() {
        return mPhone;
    }

    /**
     * Sets the phone number associated with this address.
     */
    public void setPhone(String phone) {
        mPhone = phone;
    }

    /**
     * Returns the public URL for the address if known,
     * or null if it is unknown.
     */
    public String getUrl() {
        return mUrl;
    }

    /**
     * Sets the public URL associated with this address.
     */
    public void setUrl(String Url) {
        mUrl = Url;
    }

    /**
     * Returns additional provider-specific information about the
     * address as a Bundle.  The keys and values are determined
     * by the provider.  If no additional information is available,
     * null is returned.
     *
     * <!--
     * <p> A number of common key/value pairs are listed
     * below. Providers that use any of the keys on this list must
     * provide the corresponding value as described below.
     *
     * <ul>
     * </ul>
     * -->
     */
    public Bundle getExtras() {
        return mExtras;
    }

    /**
     * Sets the extra information associated with this fix to the
     * given Bundle.
     */
    public void setExtras(Bundle extras) {
        mExtras = (extras == null) ? null : new Bundle(extras);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Address[addressLines=[");
        for (int i = 0; i <= mMaxAddressLineIndex; i++) {
            if (i > 0) {
                sb.append(',');
            }
            sb.append(i);
            sb.append(':');
            String line = mAddressLines.get(i);
            if (line == null) {
                sb.append("null");
            } else {
                sb.append('\"');
                sb.append(line);
                sb.append('\"');
            }
        }
        sb.append(']');
        sb.append(",feature=");
        sb.append(mFeatureName);
        sb.append(",admin=");
        sb.append(mAdminArea);
        sb.append(",sub-admin=");
        sb.append(mSubAdminArea);
        sb.append(",locality=");
        sb.append(mLocality);
        sb.append(",thoroughfare=");
        sb.append(mThoroughfare);
        sb.append(",postalCode=");
        sb.append(mPostalCode);
        sb.append(",countryCode=");
        sb.append(mCountryCode);
        sb.append(",countryName=");
        sb.append(mCountryName);
        sb.append(",hasLatitude=");
        sb.append(mHasLatitude);
        sb.append(",latitude=");
        sb.append(mLatitude);
        sb.append(",hasLongitude=");
        sb.append(mHasLongitude);
        sb.append(",longitude=");
        sb.append(mLongitude);
        sb.append(",phone=");
        sb.append(mPhone);
        sb.append(",url=");
        sb.append(mUrl);
        sb.append(",extras=");
        sb.append(mExtras);
        sb.append(']');
        return sb.toString();
    }

    public static final @android.annotation.NonNull Parcelable.Creator<Address> CREATOR =
        new Parcelable.Creator<Address>() {
        public Address createFromParcel(Parcel in) {
            String language = in.readString();
            String country = in.readString();
            Locale locale = country.length() > 0 ?
                new Locale(language, country) :
                new Locale(language);
            Address a = new Address(locale);

            int N = in.readInt();
            if (N > 0) {
                a.mAddressLines = new HashMap<Integer, String>(N);
                for (int i = 0; i < N; i++) {
                    int index = in.readInt();
                    String line = in.readString();
                    a.mAddressLines.put(index, line);
                    a.mMaxAddressLineIndex =
                        Math.max(a.mMaxAddressLineIndex, index);
                }
            } else {
                a.mAddressLines = null;
                a.mMaxAddressLineIndex = -1;
            }
            a.mFeatureName = in.readString();
            a.mAdminArea = in.readString();
            a.mSubAdminArea = in.readString();
            a.mLocality = in.readString();
            a.mSubLocality = in.readString();
            a.mThoroughfare = in.readString();
            a.mSubThoroughfare = in.readString();
            a.mPremises = in.readString();
            a.mPostalCode = in.readString();
            a.mCountryCode = in.readString();
            a.mCountryName = in.readString();
            a.mHasLatitude = in.readInt() == 0 ? false : true;
            if (a.mHasLatitude) {
                a.mLatitude = in.readDouble();
            }
            a.mHasLongitude = in.readInt() == 0 ? false : true;
            if (a.mHasLongitude) {
                a.mLongitude = in.readDouble();
            }
            a.mPhone = in.readString();
            a.mUrl = in.readString();
            a.mExtras = in.readBundle();
            return a;
        }

        public Address[] newArray(int size) {
            return new Address[size];
        }
    };

    public int describeContents() {
        return (mExtras != null) ? mExtras.describeContents() : 0;
    }

    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(mLocale.getLanguage());
        parcel.writeString(mLocale.getCountry());
        if (mAddressLines == null) {
            parcel.writeInt(0);
        } else {
            Set<Map.Entry<Integer, String>> entries = mAddressLines.entrySet();
            parcel.writeInt(entries.size());
            for (Map.Entry<Integer, String> e : entries) {
                parcel.writeInt(e.getKey());
                parcel.writeString(e.getValue());
            }
        }
        parcel.writeString(mFeatureName);
        parcel.writeString(mAdminArea);
        parcel.writeString(mSubAdminArea);
        parcel.writeString(mLocality);
        parcel.writeString(mSubLocality);
        parcel.writeString(mThoroughfare);
        parcel.writeString(mSubThoroughfare);
        parcel.writeString(mPremises);
        parcel.writeString(mPostalCode);
        parcel.writeString(mCountryCode);
        parcel.writeString(mCountryName);
        parcel.writeInt(mHasLatitude ? 1 : 0);
        if (mHasLatitude) {
            parcel.writeDouble(mLatitude);
        }
        parcel.writeInt(mHasLongitude ? 1 : 0);
        if (mHasLongitude){
            parcel.writeDouble(mLongitude);
        }
        parcel.writeString(mPhone);
        parcel.writeString(mUrl);
        parcel.writeBundle(mExtras);
    }
}

我尝试了几个组合,但没有一个能告诉我地址。虽然我的应用程序的前一个版本上的相同代码运行良好。旧版本应用程序中返回的地址为:

地址[addressLines=[0:"俄亥俄,美国"],功能=俄亥俄,admin=俄亥俄,sub-admin=null,locality=null,通途=null,postalCode=null,国家代码=美国,国家名称=美国,hasLati纬度=true,纬度=40.417287099999996,hasLongity=true,经度=-82.90712300000001,电话=null,url=null,额外的=null]

日志。e(“TTAG2”,“”new Gson()。toJson(新的可搜索地址(address));上一版本中的部分代码返回地址:

{“mAddressLines”:{“0”:“Ohio,USA”},“mAdminArea”:“Ohio”,“McCountryCode”:“US”,“McCountryName”:“US”,“mFeatureName”:“Ohio”,“mHasLatitude”:true,“mHasLatitude”:true,“mLatitude”:40.4172870999996,“mLocale”:“en\u US”,“mLongitute”:-82.90712300000001,“mMaxAddressLineIndex”:0}

和我上面的代码想要的一样。

我也得到了这个lint问题,这无论如何是这个问题的责任-过时的proguard文件;使用-keepclasseswithmembers而不是-keepclasseswithmembernames

共有1个答案

水恩
2023-03-14

我自己创建了Address类

@Data
@AllArgsConstructor
public class Address {

    List<String> addressLine;
    String feature;
    String admin;
    String subAdmin;
    String locality;
    String thoroughfare;
    Integer postalCode;
    String countryCode;
    String countryName;
    Boolean hasLatitude;
    Double latitude;
    Boolean hasLongitude;
    Double longitude;
    String phone;
    String url;
    String[] extras;

    public String getAddressLine(int index) {
        return addressLine.get(index);
    }
}

然后我创建了测试地址来测试

    public static void main(String args[]) {
        List<String> ohious = new ArrayList<>();
        ohious.add("Ohio, USA");
        Address address = new Address(ohious, "Ohio", "Ohio", null, null, null, null, "US", "United States", true, 40.41, true, -82.90, null, null, null);
        List<Address> ls = new ArrayList<>();
        ls.add(address);
        List<SearchableAddress> searchableAddresses = convertAddressToSearchableAddress(ls);
        System.out.println(searchableAddresses);
    }

    private static List<SearchableAddress> convertAddressToSearchableAddress(final List<Address> addressList) {

        final List<SearchableAddress> toReturn = new ArrayList<>();

        for (final Address address : addressList) {

            Gson gson = new GsonBuilder().serializeNulls().create();
            // Then I've also tried this:
            SearchableAddress searchableAddress=new SearchableAddress(address);

            String json = gson.toJson(searchableAddress);

            System.out.println("Finally we have address---> "+json); //This one is returning-->{"address":{},"fullAddress":null}

            System.out.println("TTAG2 "+gson.toJson(searchableAddress)); //Being the same as above, this one is returning----

            toReturn.add(new SearchableAddress(address));
        }
        return toReturn;
    }

输出如下所示:

Finally we have address---> {"address":{"addressLine":["Ohio, USA"],"feature":"Ohio","admin":"Ohio","subAdmin":null,"locality":null,"thoroughfare":null,"postalCode":null,"countryCode":"US","countryName":"United States","hasLatitude":true,"latitude":40.41,"hasLongitude":true,"longitude":-82.9,"phone":null,"url":null,"extras":null},"fullAddress":null}
TTAG2 {"address":{"addressLine":["Ohio, USA"],"feature":"Ohio","admin":"Ohio","subAdmin":null,"locality":null,"thoroughfare":null,"postalCode":null,"countryCode":"US","countryName":"United States","hasLatitude":true,"latitude":40.41,"hasLongitude":true,"longitude":-82.9,"phone":null,"url":null,"extras":null},"fullAddress":null}

我认为问题是您在address类中以某种方式创建了kebab case变量

子管理员=空

 类似资料:
  • 用户错误报告显示偶尔会返回,但对于大多数用户来说,它工作正常。 我访问了一位用户,他在手机上遇到了错误并调试了应用程序,我制作了来显示发送到服务器的内容,我看到Toast显示了,并且记录和ID不是。 这是我所做的。 这里我做序列化对象 但是)对于一些用户来说是正确的,但是对于一些用户来说返回 服务器数据库显示一些用户发送了数据,但一些用户发送了正确的json。经过一些研究,我发现了新的Gson()

  • 我是MongoDB的新手,在这里有点疯狂。我正在使用最新的mongo java驱动程序版本和dropwizard。 我使用POJO向DDBB写入数据,这很有效。但是,在尝试获取元素时,我没有获得实际的\u id。以下是我尝试的内容: DDBB文档 人物类 返回值: 如您所见,它不会返回实际的id(例如603c249cbb33487d9baa49f8)。我尝试将id设置为字符串,但我得到的错误是解码

  • 我正在尝试使用方法,但它正在重新生成类的对象哈希代码,例如: 但是,我可以检索用户。没有任何问题和所有关系的专业知识: 这是我的Gson方法: 这是我的MyTypeAdapter: } 那么,如何让实际返回一个Json字符串,以便我可以使用Gson. FromJson在我的另一端?提前谢谢。

  • 我正在使用Spring4 MVC创建一个REST API。我希望能够在请求无效endpoint时提供一个默认的JSON错误对象。我读过关于@ControllerAdvice和@ExceptionHandler的文章,我试图正确使用它们: 我的ErrorResponse类如下所示: 我修改了web.xml,以便抛出NoHandlerFound异常: 然后返回标准Tomcat404页。请不要说: >

  • 描述 (Description) 它使用JSON格式返回集合中每个模型的属性哈希的副本。 语法 (Syntax) collection.toJSON(options) 参数 (Parameters) options - 它包含选项作为集合实例并将其转换为JSON格式。 例子 (Example) <!DOCTYPE html> <html> <head> <title>Colle

  • 描述 (Description) 它返回属性的副本作为JSON字符串化的对象。 语法 (Syntax) model.toJSON(options) 参数 (Parameters) options - 它定义参数,例如变量名称,返回模型属性的浅表副本时用于模型的id。 例子 (Example) <!DOCTYPE html> <html> <head> <title> Model