用Gson反序列化Json以在TextViews中显示信息

时间:2018-09-23 17:26:31

标签: java android json

我已经尝试了几天,用GSON反序列化这样的JSON。

 {
"upcoming": [
    "silver",
    "gold",
    "silver",
    "silver",
    "silver",
    "silver",
    "gold",
    "silver",
    "silver"
],
"superMagical": 559,
"magical": 19,
"legendary": 79,
"epic": 699,
"giant": 94
 }

您知道我如何在不同的TextViews中显示此信息吗?

我设法反序列化了其他更简单的Json,并在TextViews中显示了它们的信息,但这让我头疼。

我的想法是创建一个名为Chests的类,这就是代码:

public class chests implements Serializable {


public int superMagical;
public int magical;
public int legendary;
public int epic;
public int giant;
}

然后,在另一堂课中,我将做以下事情

public class ClashChest implements Serializable {

@SerializedName("")
@Expose
public chests chestData; //

List<Upcoming> upcoming;
}

最后在我希望显示信息的活动中,我会这样做

public class ChestActivity extends AppCompatActivity {

public ClashChest datachest;
public TextView chest1, chest2, chest3, chest4;

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

    datachest = (ClashChest)getIntent().getSerializableExtra("cofres");

    chest1 = findViewById(R.id.chest1txt);
    chest2 = findViewById(R.id.chest2txt);
    chest3 = findViewById(R.id.chest3txt);
    chest4 = findViewById(R.id.chest4txt);

    chest1.setText("" + datachest.chestData.legendary);

}
}

要在活动之间传递信息,我需要带有以下代码的按钮

 btnCofre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (!inputUser.getText().toString().isEmpty()) {


                OkHttpClient client = new OkHttpClient();


                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);

                Request request = new Request.Builder()
                        .url("https://api.royaleapi.com/player/" + inputUser.getText().toString() + "/chests")
                        .get()
                        .addHeader("auth", "Whatever")
                        .build();


                try {

                    Response response = client.newCall(request).execute();
                    String json = response.body().string();



                    if (response.isSuccessful()) {


                        Gson gson = new Gson();

                        ClashChest clashChest = gson.fromJson(json, ClashChest.class);

                        Intent intent;
                        intent = new Intent(MainActivity.this, ChestActivity.class);
                        intent.putExtra("cofres", clashChest);
                        startActivity(intent);


                    } 




    });

1 个答案:

答案 0 :(得分:1)

我会说创建一个与您的对象匹配的类,然后让GSON进行反序列化。 你有这个:

 {
"upcoming": [
    "silver",
    "gold",
    "silver",
    "silver",
    "silver",
    "silver",
    "gold",
    "silver",
    "silver"
],
"superMagical": 559,
"magical": 19,
"legendary": 79,
"epic": 699,
"giant": 94
 }

等效类为:

public class Foo {
    List<String> upcoming;
    int superMagical;
    int magical;
    int legendary;
    int epic;
    int giant;

    // eventually other functions, getter/setter...
}

然后反序列化它:

Foo targetObject = new Gson().fromJson(yourJson, Foo.class);

最后,您可以通过以下方式在视图中显示它:

yourTextview.setText(String.valueOf(targetObject.yourField)) // for the integers
yourTextview.setText(String.join(",", targetObject.upcoming)); // displays all values from upcoming separated by a coma

对于该字符串,您可能还希望使用列表视图

编辑: 对于我从添加的代码中看到的内容,您的ClashChest类与您尝试解析的json不匹配。转换为json时,您可以考虑将一个类表示为json对象。因此,在这里,您的ClashChest类一旦转换为JSON就会像这样:

public class ClashChest implements Serializable {

@SerializedName("")
@Expose
public chests chestData; //

List<Upcoming> upcoming;
}

将是

{
    "chestData": 
    {
        // all the fieds you have in your chests class
    },
    "upcoming": // an array that contains x upcoming objects
    [
        {
            // every field you have in your Upcoming class
        }
    ]
}

如果要匹配json,则应将所有内容放在一起。即将到来的数组仅包含字符串,不包含对象,因此,如果要匹配对象,将是这样的:

public class Chest implements Serializable {
    List<String> upcoming;
    int superMagical;
    int magical;
    int legendary;
    int epic;
    int giant;
}