<iframe frameborder="no" height="240" src="https://catalogue.codepowders.com" style="position: absolute; width: 100%; height: 100%; left: 0; top: 0" width="320"></iframe>
新建一个Person类
/** * Created by Mr.Chan * Time 2022-11-15 * Blog https://www.cnblogs.com/Frank-dev-blog/ */ public class Person { private String id; private String name; private String age; public void setId(String id){ this.id = id; } public String getId(){ return this.id; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setAge(String age){ this.age = age; } public String getAge(){ return this.age; } @Override public String toString() { return this.name + "age:" + this.age; } }
String json="[\n" + " { \"id\":\"1\",\"name\":\"小明\",\"age\":\"16\" },\n" + " { \"id\":\"2\",\"name\":\"小红\",\"age\":\"17\" },\n" + " { \"id\":\"3\",\"name\":\"小绿\",\"age\":\"18\" }\n" + "]";
这是json
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for(Person person:parseEasyJson(json)){ Log.e("--->",person.toString()); } } String json="[\n" + " { \"id\":\"1\",\"name\":\"小明\",\"age\":\"16\" },\n" + " { \"id\":\"2\",\"name\":\"小红\",\"age\":\"17\" },\n" + " { \"id\":\"3\",\"name\":\"小绿\",\"age\":\"18\" }\n" + "]"; private ArrayList<Person> parseEasyJson(String json){ ArrayList<Person> persons = new ArrayList<Person>(); try{ JSONArray jsonArray = new JSONArray(json); for(int i = 0;i < jsonArray.length();i++){ JSONObject jsonObject = (JSONObject) jsonArray.get(i); Person person = new Person(); person.setId(i+""); person.setName(jsonObject.getString("name")); person.setAge(jsonObject.getString("age")); persons.add(person); } }catch (Exception e){e.printStackTrace();} return persons; } }
这是MainActivity,最精彩的部分是,创建一个类的动态数组,把信息放到Person对象里面,再foreach出来
GitHub地址 下载前给star
标签:String,age,public,json,android,解析,id,name From: https://www.cnblogs.com/Frank-dev-blog/p/16892103.html