Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Last active July 20, 2018 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/077bf35288aa39e21723196e6305d4f8 to your computer and use it in GitHub Desktop.
Save ssaurel/077bf35288aa39e21723196e6305d4f8 to your computer and use it in GitHub Desktop.
Main Activity code for the Fastjson tutorial on the SSaurel's Blog
package com.ssaurel.fastjson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
public class MainActivity extends AppCompatActivity {
private TextView resultTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTv = findViewById(R.id.resultTv);
// display encode result
Groups groups = createData();
String json = encode(groups);
resultTv.setText(json);
// decode with fast JSON (next step)
groups = decode(json);
for (Group group : groups.getGroups()) {
// iterate on groups ...
}
}
public Groups createData() {
Groups groups = new Groups();
Group group1 = new Group();
groups.addGroup(group1);
Group group2 = new Group();
groups.addGroup(group2);
group1.setId(0L);
group1.setName("Admin");
group2.setId(1L);
group2.setName("Moderators");
User user = new User();
user.setId(0L);
user.setName("Sylvain Saurel");
group1.addUser(user);
user = new User();
user.setId(1L);
user.setName("Claude Saurel");
group1.addUser(user);
user = new User();
user.setId(2L);
user.setName("Rachida Saurel");
group2.addUser(user);
return groups;
}
public String encode(Groups groups) {
// Encode POJO hierarchy to JSON quickly with Fastjson
return JSON.toJSONString(groups); // That's All !
}
public Groups decode(String json) {
// Decode JSON in String format and bind it in Groups Java POJO Hierarchy
return JSON.parseObject(json, Groups.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment