Android-GSON parses JSON

Add jar package

implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.google.code.gson:gson:2.7'

Apply for network permissions in the closure

<uses-permission android:name="android.permission.INTERNET"/>

There is only a Button in the layout file, which will not be explained here. The parsed XML data will be reflected in the log mode.
Create an entity class. The fields in the User and User are mapped to the tags in the json data. The
code is as follows:

public class User {
    private String id;
    private String name;
    private String version;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

The MainActivity.java code is as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button SendRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SendRequest = (Button) findViewById(R.id.SendRequest);
        SendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.SendRequest){
            SendRequestToJson();
        }
    }
    private void SendRequestToJson(){
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("http://192.168.0.60:8888/data.json").build();
            Response response = client.newCall(request).execute();
            String ResponseData = response.body().string();
            JsonParseWithGson(ResponseData);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void JsonParseWithGson(String Data){
        Gson gson = new Gson();
        /*
        * 由于在运行期间无法得知User的具体类型,
        * 对这个类的对象进行序列化和反序列化都不能正常进行
        * Gson通过借助TypeToken类来解决这个问题。
        * 将User类作为TypeToken的一个匿名子类然后通过getType()获取类的参数类型
        * */


        List<User> userList = gson.fromJson(Data,new TypeToken<List<User>>(){}.getType());
        for (User user : userList){
            Log.d("ID =",user.getId());
            Log.d("Name =",user.getName());
            Log.d("Version =",user.getVersion());
        }
    }
}

Guess you like

Origin blog.csdn.net/News53231323/article/details/113844860