精华内容
下载资源
问答
  • Android 下用GSON示例

    2016-01-11 14:02:06
    Android基于Gson序列化和反序列化,用于存储对象到xml和从xml中解析对象
  • gson 解析jsonWelcome to Gson Example Tutorial. In last post we looked at the Java JSON API and you can easily tell that it’s not convenient to use it. Whether you have to convert JSON to Java Object ...

    gson 解析json

    Welcome to Gson Example Tutorial. In last post we looked at the Java JSON API and you can easily tell that it’s not convenient to use it. Whether you have to convert JSON to Java Object or otherwise, you need to write a lot of code that is tightly coupled with the JSON structure.

    欢迎使用Gson示例教程。 在上一篇文章中,我们研究了Java JSON API ,您可以很容易地看出使用它并不方便。 无论您是否必须将JSON转换为Java Object,都需要编写大量与JSON结构紧密结合的代码。

    格森 (Gson)

    I started looking out for some other JSON parser API that can do the transformation itself and found about Google Gson. Gson is an open source code and it’s used a lot in working with JSON and Java. Gson uses Java Reflection to provide simple methods to convert JSON to java and vice versa.

    我开始寻找其他可以自行完成转换的JSON解析器API,并找到了有关Google Gson的信息。 Gson是一个开放源代码,在JSON和Java中已被大量使用。 Gson使用Java Reflection提供简单的方法来将JSON转换为Java,反之亦然。

    格森·Maven (Gson Maven)

    You can download Gson jar file from google code website or if you are using maven then all you need is to add it’s dependency like below.

    您可以从Google代码网站下载Gson jar文件,或者如果您使用的是maven,则只需添加它的依赖项,如下所示。

    <dependencies>
        <!--  Gson dependency -->
        <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.2.4</version>
        </dependency>
    </dependencies>

    Gson is very powerful API and it supports Java Generics. Gson API also supports out of the box JSON to Java Object conversion if the object field names are same as in json. If we want to use different name for java bean and json, then we can use @SerializedName java annotation and map the variables in JSON and Java Class.

    Gson是非常强大的API,它支持Java泛型 。 如果对象字段名称与json中的相同,则Gson API还支持将JSON转换为Java Object。 如果要为Java bean和json使用不同的名称,则可以使用@SerializedName java批注并在JSON和Java类中映射变量。

    格森的例子 (Gson Example)

    Let’s look at a complex Gson example that involves nested object and array in JSON and we will map it to java bean properties of type List, Map, Array etc.

    让我们看一个复杂的Gson示例,该示例涉及JSON中的嵌套对象和数组,并将其映射到类型为List,Map,Array等的Java bean属性。

    employee.txt

    employee.txt

    {
      "empID": 100,
      "name": "David",
      "permanent": false,
      "address": {
        "street": "BTM 1st Stage",
        "city": "Bangalore",
        "zipcode": 560100
      },
      "phoneNumbers": [
        123456,
        987654
      ],
      "role": "Manager",
      "cities": [
        "Los Angeles",
        "New York"
      ],
      "properties": {
        "age": "28 years",
        "salary": "1000 Rs"
      }
    }

    Let’s create the java bean classes to convert JSON to Java Object.

    让我们创建Java Bean类以将JSON转换为Java Object。

    Employee.java

    Employee.java

    package com.journaldev.json.model;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    import com.google.gson.annotations.SerializedName;
    
    public class Employee {
    
    	@SerializedName("empID")
    	private int id;
    	private String name;
    	private boolean permanent;
    	private Address address;
    	private long[] phoneNumbers;
    	private String role;
    	private List<String> cities;
    	private Map<String, String> properties;
    	
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public boolean isPermanent() {
    		return permanent;
    	}
    	public void setPermanent(boolean permanent) {
    		this.permanent = permanent;
    	}
    	public Address getAddress() {
    		return address;
    	}
    	public void setAddress(Address address) {
    		this.address = address;
    	}
    	public long[] getPhoneNumbers() {
    		return phoneNumbers;
    	}
    	public void setPhoneNumbers(long[] phoneNumbers) {
    		this.phoneNumbers = phoneNumbers;
    	}
    	public String getRole() {
    		return role;
    	}
    	public void setRole(String role) {
    		this.role = role;
    	}
    	
    	@Override
    	public String toString(){
    		StringBuilder sb = new StringBuilder();
    		sb.append("***** Employee Details *****\n");
    		sb.append("ID="+getId()+"\n");
    		sb.append("Name="+getName()+"\n");
    		sb.append("Permanent="+isPermanent()+"\n");
    		sb.append("Role="+getRole()+"\n");
    		sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
    		sb.append("Address="+getAddress()+"\n");
    		sb.append("Cities="+Arrays.toString(getCities().toArray())+"\n");
    		sb.append("Properties="+getProperties()+"\n");
    		sb.append("*****************************");
    		
    		return sb.toString();
    	}
    	public List<String> getCities() {
    		return cities;
    	}
    	public void setCities(List<String> cities) {
    		this.cities = cities;
    	}
    	public Map<String, String> getProperties() {
    		return properties;
    	}
    	public void setProperties(Map<String, String> properties) {
    		this.properties = properties;
    	}
    }

    Address.java

    Address.java

    package com.journaldev.json.model;
    
    public class Address {
    	
    	private String street;
    	private String city;
    	private int zipcode;
    	
    	public String getStreet() {
    		return street;
    	}
    	public void setStreet(String street) {
    		this.street = street;
    	}
    	public String getCity() {
    		return city;
    	}
    	public void setCity(String city) {
    		this.city = city;
    	}
    	public int getZipcode() {
    		return zipcode;
    	}
    	public void setZipcode(int zipcode) {
    		this.zipcode = zipcode;
    	}
    	
    	@Override
    	public String toString(){
    		return getStreet() + ", "+getCity()+", "+getZipcode();
    	}
    }

    Here is the java program showing Gson example to parse JSON.

    这是显示Gson示例以解析JSON的Java程序。

    EmployeeGsonExample.java

    EmployeeGsonExample.java

    package com.journaldev.json.gson;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.journaldev.json.model.Address;
    import com.journaldev.json.model.Employee;
    
    public class EmployeeGsonExample {
    
    	public static void main(String[] args) throws IOException {
    		Employee emp = createEmployee();
    
    		// Get Gson object
    		Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
    		// read JSON file data as String
    		String fileData = new String(Files.readAllBytes(Paths
    				.get("employee.txt")));
    
    		// parse json string to object
    		Employee emp1 = gson.fromJson(fileData, Employee.class);
    
    		// print object data
    		System.out.println("\n\nEmployee Object\n\n" + emp1);
    
    		// create JSON String from Object
    		String jsonEmp = gson.toJson(emp);
    		System.out.print(jsonEmp);
    
    	}
    
    	public static Employee createEmployee() {
    
    		Employee emp = new Employee();
    		emp.setId(100);
    		emp.setName("David");
    		emp.setPermanent(false);
    		emp.setPhoneNumbers(new long[] { 123456, 987654 });
    		emp.setRole("Manager");
    
    		Address add = new Address();
    		add.setCity("Bangalore");
    		add.setStreet("BTM 1st Stage");
    		add.setZipcode(560100);
    		emp.setAddress(add);
    
    		List<String> cities = new ArrayList<String>();
    		cities.add("Los Angeles");
    		cities.add("New York");
    		emp.setCities(cities);
    
    		Map<String, String> props = new HashMap<String, String>();
    		props.put("salary", "1000 Rs");
    		props.put("age", "28 years");
    		emp.setProperties(props);
    
    		return emp;
    	}
    }

    Gson is the main class that exposes the methods fromJson() and toJson() for conversion. For default implementation, we can create this object directly or we can use GsonBuilder class that provide useful options for conversion such as pretty printing, field naming convention, excluding fields, date format etc.

    Gson是主要类,它公开了fromJson()toJson()进行转换。 对于默认实现,我们可以直接创建此对象,也可以使用GsonBuilder类,该类提供了有用的转换选项,例如漂亮的打印,字段命名约定,排除字段,日期格式等。

    When you will run above gson example program, we will get following output for java object.

    当您在gson示例程序上方运行时,我们将为java对象获得以下输出。

    Employee Object
    
    ***** Employee Details *****
    ID=100
    Name=David
    Permanent=false
    Role=Manager
    Phone Numbers=[123456, 987654]
    Address=BTM 1st Stage, Bangalore, 560100
    Cities=[Los Angeles, New York]
    Properties={age=28 years, salary=1000 Rs}
    *****************************

    You can see how easy it is to use Gson and that’s why Gson is a very popular java API for JSON parsing.

    您可以看到使用Gson多么容易,这就是为什么Gson是非常流行的JSON解析Java API的原因。

    The above Gson example of JSON parsing is known as Object model because whole JSON is converted to object at once. Most of the times it’s enough for us but if JSON is really huge and we don’t want to have all of it in memory at once, Gson provides Streaming API too.

    上面的JSON解析的Gson示例被称为对象模型,因为整个JSON会立即转换为对象。 在大多数情况下,这对我们来说已经足够了,但是如果JSON确实非常庞大并且我们不想一次将所有内容都存储在内存中,那么Gson也会提供Streaming API

    Gson示例使用流API解析JSON (Gson Example Parse JSON using Streaming API)

    Let’s see Gson example where we will use Streaming API for json to java object conversion.

    让我们看一下Gson示例,在这里我们将使用Streaming API将json转换为java对象。

    EmployeeGsonReader.java

    EmployeeGsonReader.java

    package com.journaldev.json.gson;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import com.google.gson.stream.JsonReader;
    import com.google.gson.stream.JsonToken;
    import com.journaldev.json.model.Address;
    import com.journaldev.json.model.Employee;
    
    public class EmployeeGsonReader {
    
    	public static void main(String[] args) throws IOException {
    		InputStream is = new FileInputStream("employee.txt");
    		InputStreamReader isr = new InputStreamReader(is);
    		
    		//create JsonReader object
    		JsonReader reader = new JsonReader(isr);
    		
    		//create objects
    		Employee emp = new Employee();
    		Address add = new Address();
    		emp.setAddress(add);
    		List<Long> phoneNums = new ArrayList<Long>();
    		emp.setCities(new ArrayList<String>());
    		emp.setProperties(new HashMap<String, String>());
    		String key = null;
    		boolean insidePropertiesObj=false;
    		
    		key = parseJSON(reader, emp, phoneNums, key, insidePropertiesObj);
    		
    		
    		long[] nums = new long[phoneNums.size()];
    		int index = 0;
    		for(Long l :phoneNums){
    			nums[index++] = l;
    		}
    		emp.setPhoneNumbers(nums);
    		
    		reader.close();
    		//print employee object
    		System.out.println("Employee Object\n\n"+emp);
    	}
    	
    	
    
    	private static String parseJSON(JsonReader reader, Employee emp,
    			List<Long> phoneNums, String key, boolean insidePropertiesObj) throws IOException {
    		
    		//loop to read all tokens
    				while(reader.hasNext()){
    					//get next token
    					JsonToken token = reader.peek();
    					
    					switch(token){
    					case BEGIN_OBJECT:
    						reader.beginObject();
    						if("address".equals(key) || "properties".equals(key)){
    							while(reader.hasNext()){
    							parseJSON(reader, emp,phoneNums, key, insidePropertiesObj);
    							}
    							reader.endObject();
    						}
    						break;
    					case END_OBJECT:
    						reader.endObject();
    						if(insidePropertiesObj) insidePropertiesObj=false;
    						break;
    					case BEGIN_ARRAY:
    						reader.beginArray();
    						if("phoneNumbers".equals(key) || "cities".equals(key)){
    							while(reader.hasNext()){
    								parseJSON(reader, emp,phoneNums, key, insidePropertiesObj);
    								}
    							reader.endArray();
    						}
    						break;
    					case END_ARRAY:
    						reader.endArray();
    						break;
    					case NAME:
    						key = reader.nextName();
    						if("properties".equals(key)) insidePropertiesObj=true;
    						break;
    					case BOOLEAN:
    						if("permanent".equals(key)) emp.setPermanent(reader.nextBoolean());
    						else{
    							System.out.println("Unknown item found with key="+key);
    							//skip value to ignore it
    							reader.skipValue();
    						}
    						break;
    					case NUMBER:
    						if("empID".equals(key)) emp.setId(reader.nextInt());
    						else if("phoneNumbers".equals(key)) phoneNums.add(reader.nextLong());
    						else if("zipcode".equals(key)) emp.getAddress().setZipcode(reader.nextInt());
    						else {
    							System.out.println("Unknown item found with key="+key);
    							//skip value to ignore it
    							reader.skipValue();
    						}
    						break;
    					case STRING:
    						setStringValues(emp, key, reader.nextString(), insidePropertiesObj);
    						break;
    					case NULL:
    						System.out.println("Null value for key"+key);
    						reader.nextNull();
    						break;
    					case END_DOCUMENT:
    						System.out.println("End of Document Reached");
    						break;
    					default:
    						System.out.println("This part will never execute");
    						break;
    						
    					}
    				}
    				return key;
    	}
    
    
    
    	private static void setStringValues(Employee emp, String key,
    			String value, boolean insidePropertiesObj) {
    		if("name".equals(key)) emp.setName(value);
    		else if("role".equals(key)) emp.setRole(value);
    		else if("cities".equals(key)) emp.getCities().add(value);
    		else if ("street".equals(key)) emp.getAddress().setStreet(value);
    		else if("city".equals(key)) emp.getAddress().setCity(value);
    		else{
    			//add to emp properties map
    			if(insidePropertiesObj){
    				emp.getProperties().put(key, value);
    			}else{
    				System.out.println("Unknown data found with key="+key+" value="+value);
    			}
    			
    		}
    	}
    
    }

    Since JSON is a recursive language, we need to call our parsing method recursively for array and nested object. JsonToken is java enum returned by JsonReader next() method that we can use with conditional logic or switch case statements for conversion.

    由于JSON是一种递归语言,因此我们需要为数组和嵌套对象递归调用解析方法。 JsonToken是JsonReader next()方法返回的Java枚举 ,我们可以将其与条件逻辑一起使用或切换case语句进行转换。

    From the code above, you can understand that it’s not an easy implementation and if the JSON is really complex, then this code will become very hard to maintain. Avoid using it until unless there is no way to use Object based model.

    从上面的代码中,您可以了解到这不是一个简单的实现,并且如果JSON确实很复杂,那么此代码将很难维护。 除非没有办法使用基于对象的模型,否则请避免使用它。

    将对象写入文件的Gson示例 (Gson Example to Write Object to File)

    Let’s see how we can write Employee object using Gson Streaming API.

    让我们看看如何使用Gson Streaming API编写Employee对象。

    EmployeeGsonWriter.java

    EmployeeGsonWriter.java

    package com.journaldev.json.gson;
    
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.util.Set;
    
    import com.google.gson.stream.JsonWriter;
    import com.journaldev.json.model.Employee;
    
    public class EmployeeGsonWriter {
    
    	public static void main(String[] args) throws IOException {
    		Employee emp = EmployeeGsonExample.createEmployee();
    		
    		//writing on console, we can initialize with FileOutputStream to write to file
    		OutputStreamWriter out = new OutputStreamWriter(System.out);
    		JsonWriter writer = new JsonWriter(out);
    		//set indentation for pretty print
    		writer.setIndent("\t");
    		//start writing
    		writer.beginObject(); //{
    		writer.name("id").value(emp.getId()); // "id": 123
    		writer.name("name").value(emp.getName()); // "name": "David"
    		writer.name("permanent").value(emp.isPermanent()); // "permanent": false
    		writer.name("address").beginObject(); // "address": {
    			writer.name("street").value(emp.getAddress().getStreet()); // "street": "BTM 1st Stage"
    			writer.name("city").value(emp.getAddress().getCity()); // "city": "Bangalore"
    			writer.name("zipcode").value(emp.getAddress().getZipcode()); // "zipcode": 560100
    			writer.endObject(); // }
    		writer.name("phoneNumbers").beginArray(); // "phoneNumbers": [
    			for(long num : emp.getPhoneNumbers()) writer.value(num); //123456,987654
    			writer.endArray(); // ]
    		writer.name("role").value(emp.getRole()); // "role": "Manager"
    		writer.name("cities").beginArray(); // "cities": [
    			for(String c : emp.getCities()) writer.value(c); //"Los Angeles","New York"
    			writer.endArray(); // ]
    		writer.name("properties").beginObject(); //"properties": {
    			Set<String> keySet = emp.getProperties().keySet();
    			for(String key : keySet) writer.name("key").value(emp.getProperties().get(key));//"age": "28 years","salary": "1000 Rs"
    			writer.endObject(); // }
    		writer.endObject(); // }
    		
    		writer.flush();
    		
    		//close writer
    		writer.close();
    		
    	}
    
    }

    Converting java object to JSON is comparatively easy than parsing with Gson streaming API. By default JsonWriter writes json in compact form but we can set indent for pretty printing.

    与使用Gson流API进行解析相比,将Java对象转换为JSON相对容易。 默认情况下,JsonWriter以紧凑形式编写json,但我们可以设置缩进以进行漂亮的打印。

    That’s all for Gson example tutorial, let me know if you face any issues with it. Download project from below link and play around with different options Gson provides.

    这就是Gson示例教程的全部内容,如果您遇到任何问题,请告诉我。 从下面的链接下载项目,并尝试使用Gson提供的不同选项。

    References:

    参考文献:

    Google-Gson on Google Code
    Gson User Guide

    Google Code上的Google-Gson
    Gson用户指南

    翻译自: https://www.journaldev.com/2321/gson-example-tutorial-parse-json

    gson 解析json

    展开全文
  • GSON 示例代码 实用版

    2016-04-10 03:02:00
     GsonBean bean = gson.fromJson(json,  GsonBean. class );  System. out .println(bean.toString());  System. out .println(bean. data .get(0). username );  String json2 = gson.toJson(bean);  ...

    去除所有格式的json字符串

    {"data":[{"friend":[{"address":"广州","name":"好友1"},{"address":"深圳","name":"好友2"}],"username":"包青天"},{"friend":[],"username":"bqt"}],"num":2}

    添加转义字符后的json字符串

    {\"data\":[{\"friend\":[{\"address\":\"广州\",\"name\":\"好友1\"},{\"address\":\"深圳\",\"name\":\"好友2\"}],\"username\":\"包青天\"},{\"friend\":[],\"username\":\"bqt\"}],\"num\":2}


    { "data": [ { "friend": [ { "address": "广州", "name": "好友1" }, { "address": "深圳", "name": "好友2" } ], "username": "包青天" }, { "friend": [], "username": "bqt" } ], "num": 2 }


    public class GsonDemo {

        // 将 java 对象 格式化为 Json 字符串.
        public static void main(String[] args) {
            Gson gson = new Gson();
            String json = "{\"data\":[{\"friend\":[{\"address\":\"广州\",\"name\":\"好友1\"},{\"address\":\"深圳\",\"name\":\"好友2\"}],\"username\":\"包青天\"},{\"friend\":[],\"username\":\"bqt\"}],\"num\":2}";
            GsonBean bean = gson.fromJson(json, GsonBean.class);
            System.out.println(bean.toString());
            System.out.println(bean.data.get(0).username);
            String json2 = gson.toJson(bean);
            System.out.println("Json字符串 = " + json2);
            //******************************************************************************************
            ArrayList<Person> list_person = new ArrayList<Person>();
            list_person.add(new Person("好友1""广州"));
            list_person.add(new Person("好友2""深圳"));

            ArrayList<Account> list_account = new ArrayList<Account>();
            list_account.add(new GsonBean().new Account("包青天", list_person));//外部类GsonBean要有一个无参的构造方法,不然怎么创建内部类对象?
            list_account.add(new GsonBean().new Account("bqt"new ArrayList<Person>()));//可以是空的集合,或者直接是空对象null

            GsonBean bean2 = new GsonBean(2, list_account);
            String json3 = gson.toJson(bean2);
            System.out.println("Json字符串 = " + json3);
        }
    }

    public class Person {

        //不要求一定有get、set方法,也不要求一定有无参构造方法,甚至不要求其成员是public还是private
         //但要求所有字段名必须和json字符串中的一致
        public String name;
        public String address;
        public Person(String name, String address) {
            this.name = name;
            this.address = address;
        }
        @Override
        public String toString() {
            return "name=" + name + " & " + "address=" + address;
        }
    }

    public class GsonBean {

        public GsonBean() {
        }
        public GsonBean(int num, ArrayList<Account> data) {
            super();
            this.num = num;
            this.data = data;
        }
        public int num;
        public ArrayList<Account> data;
        /**data数组里的对象*/
        public class Account {
            public String username;
            public ArrayList<Person> friend;
            @Override
            public String toString() {
                return "账户【username=" + username + ",friend=" + friend + "】";
            }
            public Account(String username, ArrayList<Person> friend) {
                super();
                this.username = username;
                this.friend = friend;
            }
        }
        @Override
        public String toString() {
            return "Gson 【num=" + num + ",data=" + data + "】";
        }
    }





    转载于:https://www.cnblogs.com/baiqiantao/p/5373273.html

    展开全文
  • Gson使用示例

    2017-08-10 17:35:27
    写了一个简单的Gson使用示例,作为参考
  • java gson使用示例

    2021-08-13 15:19:45
    java gson使用示例 官网: https://github.com/google/gson/ maven引入 <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>...

    java gson使用示例

    官网: https://github.com/google/gson/

    maven引入

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.7</version>
    </dependency>
    

    Gson提供了fromJson() 和toJson() 两个直接用于解析和生成的方法,前者实现反序列化,后者实现了序列化;同时每个方法都提供了重载方法

    1、基本数据类型的解析
    Gson gson = new Gson();
    int i = gson.fromJson(“100”, int.class); //100
    double d = gson.fromJson("“99.99"”, double.class); //99.99
    boolean b = gson.fromJson(“true”, boolean.class); // true
    String str = gson.fromJson(“String”, String.class); // String

    2、基本数据类型的生成 
    Gson gson = new Gson();
    String jsonNumber = gson.toJson(100); // 100
    String jsonBoolean = gson.toJson(false); // false
    String jsonString = gson.toJson(“String”); //“String”

    3、POJO类的生成与解析

      public class User {
        //省略其它
         public String name;
         public int age;
         public String emailAddress;
      }
    
     生成JSON: 
        Gson gson = new Gson();
        User user = new User("张三",24);
        String jsonObject = gson.toJson(user); // {"name":"张三kidou","age":24}
     解析JSON: 
        Gson gson = new Gson();
        String jsonString = "{\"name\":\"张三\",\"age\":24}";
        User user = gson.fromJson(jsonString, User.class);
    
    展开全文
  • Gson示例 Gson 解析器示例 如何使用 Gson 解析 Json 文档 1.- 在 Android Studio 中下载 Gson 库。 在 app 文件夹中,我们打开 build.gradle 文件并在“dependencies”部分添加以下行: compile '...
  • Gson 解析示例

    2021-04-24 17:58:46
    { "bbu": { "rsTable": "wr_device_bbu", "rsPk": "bbu_id", "rsCuid": ["c3b11379-ffcd-0821-8f55-779b184b4e87"] }, "rru": { "rsTable": "wr_device_rru", "rsPk": "rru_id", "rsCuid": ["864b492f-49a0...
    {
        "bbu": {
            "rsTable": "wr_device_bbu",
            "rsPk": "bbu_id",
            "rsCuid": ["c3b11379-ffcd-0821-8f55-779b184b4e87"]
        },
        "rru": {
            "rsTable": "wr_device_rru",
            "rsPk": "rru_id",
            "rsCuid": ["864b492f-49a0-fc39-235d-3618d443b289", "ddd3437e-f42b-5f3f-e7ba-31b1592ff836", "bd323141-d2a5-866c-e4c9-ab6be8d696b5", "673d9664-70c6-6afb-9fae-b7fac7848c61", "74d1014e-52c0-bc76-141f-bc9535e5ca32", "d7230679-6cb0-ddc5-7ed5-53e5f46733e2", "cfca2be2-1b90-2b41-555a-f431eb50c6f7", "e5033d3d-ecb5-6577-1719-4de74c01929f", "1564684f-6d83-5c8f-7c9a-5750b7d49565", "8392eebd-928a-8092-bdf9-f72e7560c218", "93326c2c-f52c-d3f6-dd65-c1564034bab3", "67f0eece-6f48-9d6c-700d-af1f591b493c", "4c48bd08-fb34-c2ef-222c-850dea1996f8", "b98e7b69-49c0-5d50-
    展开全文
  • 简单GSON用法示例

    2016-12-18 17:32:44
    本文讨论并提供使用此API的简单代码示例。有关此API的详情,请访问:http://sites.google.com/site/gson/。 这是GSON系列文章的第一篇,也是其他文章的入门篇,所以不要求读者有GSON或JSON的经验。第二篇文章[todo]...
  • gson入门示例

    2011-03-07 23:29:59
    项目介绍:GSON Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象。 Gson支持任意复杂Java对象包括没有源代码的对象. Gson有2个最基本的方法 1) toJson() – 转换java 对象到JSON ...
  • android google gson json解析
  • Gson解析Json示例源码

    2017-09-13 22:54:59
    Gson类库有一个Gson类,这个Gson类提供了两个方法:toJson() 和fromJson(),我们主要就是调用这两个方法来分别实现序列化Java对象为JSON字符串和反序列化JSON...通过代码示例来对Gson类的常用方法做一个简单介绍。
  • Eclipse下使用Google Gson解析Json数据示例,挺好用的,亲测
  • Andorid Gson解析示例

    2016-06-25 15:34:00
    Gson gson = new Gson(); TypeToken, Student>> token = new com.google.gson.reflect.TypeToken<Map<String, Student>>() { }; Map, Student> stus = gson.fromJson(json, token.getType()); System.out....
  • 格森 如何使用Google的Gson库的示例
  • GSON的简单示例

    2018-04-04 11:39:00
    https://github.com/google/gson package com.example.wolf; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.BufferedReader;...
  • 一、GsonFormat / Gson 共同解析 json 文件 首先在AS的setting->plugin 中 install GsonFormat 插件,然后在app.gradle 文件中导入 Gson 解析类, implementation 'com.google.code.gson:gson:2.8.5' ...
  • 主要介绍了利用gson将map转为json示例,需要的朋友可以参考下
  • 我这次讲解一个不太复杂的示例。我使用的是Android studio,需要在gradle里添加compile'com.google.code.gson:gson:2.6.2'让其自动配置。首先拿到一个json数据,如下String json="{'status':'0','msg':'ok',&...
  • 使用示例: 首先建立一个 class public class User {   private String name ;  private int age ;  public User (String name , int age){   this . name = name ;  this . age = age ;   }   ...
  • json样本 如何使用 Google 的 Gson,Java 示例
  • Eclipse下使用Google Gson解析Json数据示例
  • 一个Android示例代码,使用Android的JSONObject和Google的gson在json和java对象之间转换数据。 此示例代码基于并经过修改以测试json和带有嵌套对象的java对象之间的转换。 创建并使用了三个自定义类: 相册(包含...
  • Android Studio下使用Google Gson解析Json数据示例
  • GSON的简单使用示例

    2017-12-05 17:28:11
          ...import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * * @ClassName Item * @author kanpiaoxue * @version 1.0 * @CreateTime 2017/12/05 16...
  • GSON是Google制作的一个可以让Java对象与JSON互相转换的类库,下面我们就来看一下Java的JSON转换库GSON的基本使用方法示例:
  • Eclipse和Android Studio下使用Google Gson解析Json数据示例Eclipse和Android Studio下使用Google Gson解析Json数据示例 一Eclipse下使用Google Gson解析Json数据示例 Gson jar包 新建Json数据所对应的Gson实体类 ...
  • 一、谷歌GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。 二、Gson解析Json步骤 A、服务器端将数据转换成json字符串 ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 8,634
精华内容 3,453
关键字:

gson示例