com.google.gson.Gson.<init>()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(313)

本文整理了Java中com.google.gson.Gson.<init>()方法的一些代码示例,展示了Gson.<init>()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Gson.<init>()方法的具体详情如下:
包路径:com.google.gson.Gson
类名称:Gson
方法名:<init>

Gson.<init>介绍

[英]Constructs a Gson object with default configuration. The default configuration has the following settings:

  • The JSON generated by toJson methods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior with GsonBuilder#setPrettyPrinting().
  • The generated JSON omits all the fields that are null. Note that nulls in arrays are kept as is since an array is an ordered list. Moreover, if a field is not null, but its generated JSON is empty, the field is kept. You can configure Gson to serialize null values by setting GsonBuilder#serializeNulls().
  • Gson provides default serialization and deserialization for Enums, Map, java.net.URL, java.net.URI, java.util.Locale, java.util.Date, java.math.BigDecimal, and java.math.BigInteger classes. If you would prefer to change the default representation, you can do so by registering a type adapter through GsonBuilder#registerTypeAdapter(Type,Object).
  • The default Date format is same as java.text.DateFormat#DEFAULT. This format ignores the millisecond portion of the date during serialization. You can change this by invoking GsonBuilder#setDateFormat(int) or GsonBuilder#setDateFormat(String).
  • By default, Gson ignores the com.google.gson.annotations.Expose annotation. You can enable Gson to serialize/deserialize only those fields marked with this annotation through GsonBuilder#excludeFieldsWithoutExposeAnnotation().
  • By default, Gson ignores the com.google.gson.annotations.Since annotation. You can enable Gson to use this annotation through GsonBuilder#setVersion(double).
  • The default field naming policy for the output Json is same as in Java. So, a Java class field versionNumber will be output as "versionNumber" in Json. The same rules are applied for mapping incoming Json to the Java classes. You can change this policy through GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy).
  • By default, Gson excludes transient or static fields from consideration for serialization and deserialization. You can change this behavior through GsonBuilder#excludeFieldsWithModifiers(int...).
    [中]使用默认配置构造Gson对象。默认配置具有以下设置:
    *toJson方法生成的JSON是紧凑的表示形式。这意味着将删除所有不需要的空白。您可以使用GsonBuilder#setPrettyPrinting()更改此行为。
    *生成的JSON会忽略所有空字段。请注意,数组中的null保持原样,因为数组是有序列表。此外,如果字段不为null,但其生成的JSON为空,则会保留该字段。通过设置GsonBuilder#serializeNulls(),可以将Gson配置为序列化空值。
    *Gson为枚举、映射和java提供默认序列化和反序列化。网URL,java。网URI,java。util。语言环境,java。util。日期,爪哇。数学BigDecimal和java。数学大整数类。如果希望更改默认表示形式,可以通过GsonBuilder#registerTypeAdapter(类型,对象)注册类型适配器来实现。
    *默认日期格式与java相同。文本日期格式#默认值。此格式在序列化期间忽略日期的毫秒部分。您可以通过调用GsonBuilder#setDateFormat(int)或GsonBuilder#setDateFormat(String)来更改此设置。
    *默认情况下,Gson忽略com。谷歌。格森。注释。公开注释。您可以通过GsonBuilder#excludeFieldsWithoutExposeAnnotation()使Gson仅序列化/反序列化标记有此注释的字段。
    *默认情况下,Gson忽略com。谷歌。格森。注释。自注释以来。您可以通过GsonBuilder#setVersion(double)启用Gson使用此注释。
    *输出Json的默认字段命名策略与Java中的相同。因此,Java类字段versionNumber将在Json中输出为"versionNumber"。同样的规则也适用于将传入的Json映射到Java类。您可以通过GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)更改此策略。
    *默认情况下,Gson将transientstatic字段排除在序列化和反序列化的考虑范围之外。您可以通过GsonBuilder#excludeFieldsWithModifiers(int…)更改此行为。

代码示例

代码示例来源:origin: stackoverflow.com

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

代码示例来源:origin: stackoverflow.com

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

System.out.println(g.toJson(person)); // {"name":"John"}

代码示例来源:origin: Bigkoo/Android-PickerView

public ArrayList<JsonBean> parseData(String result) {//Gson 解析
  ArrayList<JsonBean> detail = new ArrayList<>();
  try {
    JSONArray data = new JSONArray(result);
    Gson gson = new Gson();
    for (int i = 0; i < data.length(); i++) {
      JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
      detail.add(entity);
    }
  } catch (Exception e) {
    e.printStackTrace();
    mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
  }
  return detail;
}

代码示例来源:origin: linkedin/cruise-control

private String getJSONString(CruiseControlParameters parameters) {
 List<Map<String, Object>> jsonUserTaskList = new ArrayList<>();
 Set<UUID> requestedUserTaskIds = ((UserTasksParameters) parameters).userTaskIds();
 addFilteredJSONTasks(jsonUserTaskList, _activeUserTasks, ACTIVE_TASK_LABEL_VALUE, requestedUserTaskIds);
 addFilteredJSONTasks(jsonUserTaskList, _completedUserTasks, COMPLETED_TASK_LABEL_VALUE, requestedUserTaskIds);
 Map<String, Object> jsonResponse = new HashMap<>();
 jsonResponse.put(USER_TASKS, jsonUserTaskList);
 jsonResponse.put(VERSION, JSON_VERSION);
 return new Gson().toJson(jsonResponse);
}

代码示例来源:origin: stackoverflow.com

List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(0, "zero"));
objList.add(new DataObject(1, "one"));
String json = new Gson().toJson(objList);
System.out.println(json);
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i=0;i<inpList.size();i++) {
 DataObject x = inpList.get(i);
 System.out.println(x);

代码示例来源:origin: stackoverflow.com

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  List<String> list = new ArrayList<>();
  list.add("item1");
  list.add("item2");
  list.add("item3");
  String json = new Gson().toJson(list);

  response.setContentType("application/json");
  response.setCharacterEncoding("UTF-8");
  response.getWriter().write(json);
}

代码示例来源:origin: stackoverflow.com

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonInput2, Pojo.class);
System.out.println(pojo);

代码示例来源:origin: Vedenin/useful-java-links

/**
   * Example to writeJson using TreeModel
   */
  private static void writeJson() throws IOException {
    JsonObject rootObject = new JsonObject();
    rootObject.addProperty("message", "Hi");
    JsonObject childObject = new JsonObject();
    childObject.addProperty("name", "World!");
    rootObject.add("place", childObject);

    Gson gson = new Gson();
    String json = gson.toJson(rootObject);
    System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
  }
}

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();
 JsonElement je = gson.toJsonTree(new Foo());
 JsonObject jo = new JsonObject();
 jo.add("Foo", je);
 System.out.println(jo.toString()); //prints {"Foo":{"number":10,"str":"hello"}}

代码示例来源:origin: stackoverflow.com

//from object to JSON 
Gson gson = new Gson();
gson.toJson(yourObject);

// from JSON to object 
yourObject o = gson.fromJson(JSONString,yourObject.class);

代码示例来源:origin: zalando/zalenium

@VisibleForTesting
public static List<TestInformation> loadTestInformationFromFile() {
  try {
    List<TestInformation> testInformation = new ArrayList<>();
    File testInformationFile = new File(getLocalVideosPath(), TEST_INFORMATION_FILE);
    if (testInformationFile.exists()) {
      List<String> lines = FileUtils.readLines(testInformationFile, UTF_8);
      Gson gson = new Gson();
      for (String line : lines) {
        testInformation.add(gson.fromJson(line, TestInformation.class));
      }
    }
    return testInformation;
  } catch (Exception e) {
    LOGGER.warn(e.toString(), e);
  }
  return new ArrayList<>();
}

代码示例来源:origin: Qihoo360/XLearning

@Override
public synchronized String getClusterDef() {
 if (this.clusterDef.get(XLearningConstants.WORKER.toString()).size() == applicationContext.getWorkerNum()
   && this.clusterDef.get(XLearningConstants.PS.toString()).size() == applicationContext.getPsNum()) {
  if (this.clusterDefStr == null) {
   Collections.sort(this.clusterDef.get(XLearningConstants.PS.toString()), new compairIndex());
   Collections.sort(this.clusterDef.get(XLearningConstants.WORKER.toString()), new compairIndex());
   List workerList = new ArrayList<String>();
   List psList = new ArrayList<String>();
   for (int i = 0; i < this.clusterDef.get(XLearningConstants.WORKER.toString()).size(); i++) {
    workerList.add(this.clusterDef.get(XLearningConstants.WORKER.toString()).get(i).getHost());
   }
   for (int i = 0; i < this.clusterDef.get(XLearningConstants.PS.toString()).size(); i++) {
    psList.add(this.clusterDef.get(XLearningConstants.PS.toString()).get(i).getHost());
   }
   Map<String, List<String>> clusterMessage = new HashMap<>();
   clusterMessage.put(XLearningConstants.WORKER, workerList);
   clusterMessage.put(XLearningConstants.PS, psList);
   LOG.info("Sending cluster def \"" + new Gson().toJson(clusterMessage) + "\"to container");
   this.clusterDefStr = new Gson().toJson(clusterMessage);
  }
 }
 return this.clusterDefStr;
}

代码示例来源:origin: stackoverflow.com

List<Cars> cars= new ArrayList<Cars>();
 cars.add(a);
 cars.add(b);
 cars.add(c);
 cars.add(d);
 gson = new Gson();
 String jsonCars = gson.toJson(cars);
 Log.d("TAG","jsonCars = " + jsonCars);

代码示例来源:origin: stackoverflow.com

Type t = new TypeToken<List<SearchResult>>() {}.getType();
List<SearchResult> list = (List<SearchResult>) new Gson().fromJson("json", t);

for (SearchResult r : list) {
 System.out.println(r);
}

代码示例来源:origin: stackoverflow.com

static class PersonData {
  int age;
  String surname;
  public String toString() {
    return "[age = " + age + ", surname = " + surname + "]";
  }
}

public static void main(String[] args) {
  String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
  System.out.println(json);
  Gson gson = new Gson();
  Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
  System.out.println(decoded);
}

代码示例来源:origin: stackoverflow.com

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
 public static void main(String[] args) throws Exception
 {
  Gson gson = new Gson();
  TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
  System.out.println(gson.toJson(myTypes));
 }
}

class TypeDTO
{
 int id;
 String name;
 ArrayList<ItemDTO> items[];
}

class ItemDTO
{
 int id;
 String name;
 Boolean valid;
}

代码示例来源:origin: stackoverflow.com

Gson gson = new Gson();

String inputString= gson.toJson(inputArray);

System.out.println("inputString= " + inputString);

代码示例来源:origin: stackoverflow.com

Type listType = new TypeToken<LinkedList>() {}.getType();
List target = new LinkedList();
target.add("blah");

Gson gson = new Gson();
String json = gson.toJson(target, listType);
List target2 = gson.fromJson(json, listType);

相关文章