Как извлечь данные c из массива json с помощью дооснащения2 с использованием синтаксического анализа gson - PullRequest
2 голосов
/ 31 января 2020

Вот ответ JSON от сервера (который я не могу изменить структуру)

Мои проблемы следующие: 1. Данные изменяются в зависимости от запроса, поэтому иногда первичные сообщения и вторичные Посты - это массив, а иногда и объект / строка.

Как бы я go извлек значение из Address, не получив всю структуру? Например.
  • извлекает только адреса электронной почты и почтовые индексы из MainAddress
  • извлекает только Address1 с веб-сайта и Twitter
{
    "Members": {
    "Member": {
    "@First_Id": "000",
    "@Second_Id": "000",
    "@Third_Id": "000",
    "@Fourth_Id": "000",
    "DisplayAs": "Title FirstName LastName",
    "ListAs": "LastName, Title FirstName",
    "FullTitle": "Title Title FirstName LastName Title",
    "PreviousName": null,
    "DateOfBirth": "2020-01-01T00:00:00",
    "DateOfDeath": {
    "@xsi:nil": "true",
    "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
    },
    "Gender": "M OR F",
    "Party": {
    "@Id": "4",
    "#text": "Party Name"
    },
    "House": "House Name",
    "MemberFrom": "Area Name",
    "HouseStartDate": "2020-01-01T00:00:00",
    "HouseEndDate": {
    "@xsi:nil": "true",
    "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
    },
    "CurrentStatus": {
    "@Id": "0",
    "@IsActive": "True",
    "Name": "Current Member",
    "Reason": null,
    "StartDate": "2020-01-01T00:00:00"
    },
    "Addresses": {
    "Address": [
    {
    "@Type_Id": "6",
    "Type": "Website",
    "IsPreferred": "False",
    "IsPhysical": "False",
    "Note": null,
    "Address1": "https://www.example.co.uk"
    },
    {
    "@Type_Id": "1",
    "Type": "MainAddress",
    "IsPreferred": "False",
    "IsPhysical": "True",
    "Note": null,
    "Address1": "Line 1",
    "Address2": "Line 2",
    "Address3": "Line 3",
    "Address4": null,
    "Address5": "County Name",
    "Postcode": "Postcode",
    "Phone": "000 0000 000",
    "Fax": "000 0000 000",
    "Email": "example@email.co.uk",
    "OtherAddress": null
    },
    {
    "@Type_Id": "7",
    "Type": "Twitter",
    "IsPreferred": "False",
    "IsPhysical": "False",
    "Note": null,
    "Address1": "https://twitter.com/twitter_name"
    },
    {
    "@Type_Id": "4",
    "Type": "Address2",
    "IsPreferred": "False",
    "IsPhysical": "True",
    "Note": null,
    "Address1": "Line1",
    "Address2": "Line2",
    "Address3": "Line3",
    "Address4": "Line4",
    "Address5": null,
    "Postcode": "Postcode",
    "Phone": "0000 000 000",
    "Fax": null,
    "Email": "example2@email.co.uk",
    "OtherAddress": null
    }
    ]
    },
    "PrimaryPosts": {
    "PrimaryPost": [
    {
    "@Id": "000",
    "Name": "Name",
    "ProperName": "The Name",
    "StartDate": "2020-01-01T00:00:00",
    "EndDate": "2020-01-01T00:00:00",
    "Note": null,
    "EndNote": null,
    "IsJoint": "False",
    "IsUnpaid": "False",
    "Email": null,
    "FormerName": "Name"
    },
    {
    "@Id": "000",
    "Name": "Name",
    "ProperName": "The Name",
    "StartDate": "2020-01-01T00:00:00",
    "EndDate": "2020-01-01T00:00:00",
    "Note": null,
    "EndNote": null,
    "IsJoint": "False",
    "IsUnpaid": "False",
    "Email": null,
    "FormerName": "Name"
    }
    ]
    },
    "FormerPosts": {
    "FormerPost": [
    {
    "@Id": "000",
    "Name": "Name",
    "ProperName": "The Name",
    "StartDate": "2020-01-01T00:00:00",
    "EndDate": "2020-01-01T00:00:00",
    "Note": null,
    "EndNote": null,
    "IsJoint": "False",
    "IsUnpaid": "False",
    "Email": null
    },
    {
    "@Id": "000",
    "Name": "Name",
    "ProperName": "The Name",
    "StartDate": "2020-01-01T00:00:00",
    "EndDate": "2020-01-01T00:00:00",
    "Note": null,
    "EndNote": null,
    "IsJoint": "False",
    "IsUnpaid": "False",
    "Email": null
    }
    ]
    },
    "BiographyEntries": {
    "BiographyEntry": [
    {
    "@Category_Id": "1",
    "Category": "Interest 1",
    "Entry": "Value1, Value2, Value3, Value4"
    },
    {
    "@Category_Id": "2",
    "Category": "Interest 2",
    "Entry": "Value1, Value2, Value3, Value4"
    }
    ]
    }
    }
    }
    }

Мой текущий код для Синтаксический анализ:

    public class Main Activity extends AppcompatActivity {

    private DataCallAPI dataCallAPI;
    private static final String BASE_URL = "http://example.co.uk/data/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    dataCallAPI = retrofit.create(DataCallAPI.class);
    Call<RootObject> call = dataCallAPI.getMember(postcode);

    call.enqueue(new Callback<RootObject>() {
        @Override
        public void onResponse(Call<RootObject> call, Response<RootObject> response) {
        Log.d("JSON Log D", "onResponse: Server Response" + response.toString()+ "\n\n");

    RootObject callData= response.body();

    ArrayList<Address> addressList = 
        response.body().getMembers().getMember().getAddresses().getAddress();
        for( int i = 0; i < addressList.size(); i++) {

        Log.d("JSON Log D", "onResponse: \n" +
        addressList.get(i).getType() + " Address: " + addressList.get(i).getAddress1() + "\n" +
        addressList.get(i).getType() + " Number: " + addressList.get(i).getPhone() + "\n" +
        addressList.get(i).getType() + " Email: " + addressList.get(i).getEmail() + "\n" +
        "------------------------------------------------------------------\n\n");
    }
    }

    @Override
    public void onFailure(Call<RootObject> call, Throwable t) {
        Log.e("JSON Log E", "onFailure: Something went wrong: " + t.getMessage() );
        Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_SHORT).show();
    }
    });
    }

У меня есть модели настройки для всех POJO, которые я могу, но модель для адресов, которая содержит ArrayList или Object, не будет работать в зависимости от возвращаемых данных json.

    package com.example.retrofittutorialbuild.Model;

    import java.util.ArrayList;

    import com.example.retrofittutorialbuild.Model.Address.Address;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Addresses {

        @SerializedName("Address")
        @Expose
        private ArrayList<Address> address = null;

        public ArrayList<Address> getAddress() { return address;}

    @Override
    public String toString() {
        return "Addresses{" +
        "address=" + address +
        '}';
    }
}

Текущий ответ, который я получаю:

2020-01-31 11:18:35.058 27987-27987/com.example.retrofittutorialbuild D/JSON Log D: onResponse: 
    Website Address: http://www.exampleurl.co.uk
    Website Number: null
    Website Email: null
    ------------------------------------------------------------------
2020-01-31 11:18:35.058 27987-27987/com.example.retrofittutorialbuild D/JSON Log D: onResponse: 
    MainAddress Address: example address
    MainAddress Number: 000 0000 000
    MainAddress Email: email@example.co.uk
    ------------------------------------------------------------------
2020-01-31 11:18:35.058 27987-27987/com.example.retrofittutorialbuild D/JSON Log D: onResponse: 
    Twitter Address: https://twitter.com/example
    Twitter Number: null
    Twitter Email: null
    ------------------------------------------------------------------
2020-01-31 11:18:35.058 27987-27987/com.example.retrofittutorialbuild D/JSON Log D: onResponse: 
    Address2 Address: example address
    Address2 Number: 000 0000 000
    Address2 Email: email@example.co.uk
    ---------------------------------------------------------------------
...