Java Code Examples for com.google.gson.Gson.toJson()

The following are Jave code examples for showing how to use toJson() of the com.google.gson.Gson class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Android-Development   File: StorageUtil.java   View Source Code Vote up 6 votes
/****************************Methods used to operate one FAVORITE POIs******************************************/

    public void saveToFavoritesPOI(ParcelablePOI poi) {
        if (poi == null) return;
        preferences = context.getSharedPreferences(FAVORITES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        ArrayList<ParcelablePOI> previouslyStored = getFavoritePOIs();
        if (previouslyStored == null) {
            //No previous data
            previouslyStored = new ArrayList<>();
        }
        previouslyStored.add(0, poi);//add always new POIs to first position
        //Store FAVORITES
        Gson gson = new Gson();
        String json = gson.toJson(previouslyStored);
        editor.putString("FAVORITES", json);
        editor.apply();
    }
 
Example 2
Project: lacomida   File: PreferencesHelper.java   View Source Code Vote up 6 votes
private static <T, K> T parseSet(String json, Class<K> keyClass) {
	Set<K> resultSet = new HashSet<>();
	if (keyClass == null) {
		return (T) resultSet;
	}

	Gson gson = getGson();
	Set<K> set = gson.fromJson(json, new TypeToken<Set<K>>() {
	}.getType());

	for (K value : set) {
		String valueJson = gson.toJson(value);
		resultSet.add(gson.fromJson(valueJson, keyClass));
	}
	return (T) resultSet;
}
 
Example 3
Project: ImageClassify   File: AdminController.java   View Source Code Vote up 6 votes
/**
 * 
 * @param response
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/admin/getimgamountdata", method = RequestMethod.POST)
public void getImgAmounData(HttpServletResponse response, HttpServletRequest request) throws IOException {

	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8"); // 设置响应responce编码为utf-8
	PrintWriter out = response.getWriter();
	String json;
	Gson gson = new Gson();
	Assign assign = new Assign();

	long amount10 = imageService.getAmountOfDefinedTask(10);
	long amount20 = imageService.getAmountOfDefinedTask(20);
	long amount30 = imageService.getAmountOfDefinedTask(30);
	long all_task_amount = amount10 + amount20 + amount30;
	assign.setAmount10(amount10 + "");
	assign.setAmount20(amount20 + "");
	assign.setAmount30(amount30 + "");
	assign.setAll_task_amount(all_task_amount + "");

	Message<Assign> message = new Message<Assign>("200", "", assign);// 初始化message对象
	json = gson.toJson(message, Message.class); // 使用gson将Message对象转化为字符串
	out.print(json);
}
 
Example 4
Project: catalog-search-service   File: SearchController.java   View Source Code Vote up 6 votes
/**
 * Returns from a given concept the data properties and obejctproperties and
 * to each objecproperty a concept in the case the step range is greater 1
 * 
 * @param concept
 * @param step
 *            range
 * @param
 * @return
 */
@CrossOrigin
@RequestMapping(value = "/executeSPARQLSelect", method = RequestMethod.GET)
HttpEntity<Object> executeSPARQLSelect(@RequestParam("inputAsJson") String inputAsJson) {
	Logger.getAnonymousLogger().log(Level.INFO, "Invoke: executeSPARQLSelect: " + inputAsJson);
	OutputForExecuteSelect outputForExecuteSelect = new OutputForExecuteSelect();
	try {
		Gson gson = new Gson();
		InputParamaterForExecuteSelect inputParamaterForExecuteSelect = gson.fromJson(inputAsJson,
				InputParamaterForExecuteSelect.class);

		outputForExecuteSelect = sparqlDerivation.createSPARQLAndExecuteIT(inputParamaterForExecuteSelect);

		String result = "";
		result = gson.toJson(outputForExecuteSelect);

		return new ResponseEntity<Object>(result, HttpStatus.OK);
	} catch (Exception e) {
		return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
	}

}
 
Example 5
Project: Mobike   File: RouteService.java   View Source Code Vote up 6 votes
@Override
public void onDestroy() {
    super.onDestroy();
    mlocationClient.stop();
    myOrientationListener.stop();
    Log.d("gaolei", "RouteService----0nDestroy---------------");
    Gson gson = new Gson();
    String routeListStr = gson.toJson(routPointList);
    Log.d("gaolei", "RouteService----routeListStr-------------" + routeListStr);
    Bundle bundle = new Bundle();
    bundle.putString("totalTime", totalTime + "");
    bundle.putString("totalDistance", totalDistance + "");
    bundle.putString("totalPrice", totalPrice + "");
    bundle.putString("routePoints", routeListStr);
    Intent intent = new Intent(this, RouteDetailActivity.class);
    intent.putExtras(bundle);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    if (routPointList.size() > 2)
        insertData(routeListStr);
    Utils.releaseWakeLock();
    stopForeground(true);
}
 
Example 6
Project: ImageClassify   File: ImageUploadController.java   View Source Code Vote up 5 votes
/**
 * 管理员获取志愿者上传的贡献压缩包
 * 
 * @param start
 * @param page_num
 * @param response
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/admin/getcontributeuploadziplist", method = RequestMethod.POST)
public void getUploadZipListByUserList(@RequestParam("start") String start,
		@RequestParam("page_num") String page_num, HttpServletResponse response, HttpServletRequest request)
		throws IOException {
	// 设置编码格式
	response.setCharacterEncoding("UTF-8");
	request.setCharacterEncoding("UTF-8");

	String json = "";
	Gson gson = new Gson();
	PrintWriter out = response.getWriter();
	SplitObject<ContributeImgListOfAll> splitObject = new SplitObject<ContributeImgListOfAll>();
	List<ContributeImgListOfAll> cImgs = new ArrayList<ContributeImgListOfAll>();
	// 分页查询志愿者上传贡献的压缩包列表
	cImgs = contributeService.getContributeOfAllByUser(new Integer(start).intValue(),
			new Integer(page_num).intValue());
	splitObject.setList(cImgs);
	// 计算数据的页数
	int num = contributeService.getAmountContributeOfAllByUser();
	if (num % Constant.DEVI_NUM == 0) {
		splitObject.setPages_num(num / Constant.DEVI_NUM);
	} else {
		splitObject.setPages_num(num / Constant.DEVI_NUM + 1);
	}

	// 查询有记录
	Message<SplitObject<ContributeImgListOfAll>> message = new Message<SplitObject<ContributeImgListOfAll>>("200",
			"", splitObject);
	json = gson.toJson(message);
	out.print(json);
}
 
Example 7
Project: hypertrack-live-android   File: SharedPreferenceManager.java   View Source Code Vote up 5 votes
public static void setHyperTrackLiveUser(Context context, HyperTrackLiveUser user) {
    SharedPreferences.Editor editor = getEditor(context);

    Gson gson = new Gson();
    String userJSON = gson.toJson(user);

    editor.putString(HYPERTRACK_LIVE_USER, userJSON);
    editor.apply();
}
 
Example 8
Project: jwx   File: MassMsgService.java   View Source Code Vote up 5 votes
/**
 * 群发消息预览
 * @param accessToken
 * @param message
 * @param touser 公众号的openid
 * @param towxname 微信号
 * @return
 */
public MassReturnCode preview(String accessToken, MassMessage message, String touser, String towxname) {
	Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
	String msgText = gson.toJson(message);
	@SuppressWarnings("unchecked")
	Map<String, Object> msgMap = gson.fromJson(msgText, HashMap.class);
	
	if(msgMap.get("filter")!=null){
		msgMap.remove("filter");
	}
	if(msgMap.get("touser")!=null){
		msgMap.remove("touser");
	}
	if(msgMap.get("send_ignore_reprint")!=null){
		msgMap.remove("send_ignore_reprint");
	}
	if(towxname!=null){
		msgMap.put("towxname", towxname);
	}else if(touser!=null){
		msgMap.put("touser", touser);
	}else{
		throw new IllegalArgumentException("群发消息预览参数不符合要求,touser和towxname不能都为空。");
	}
	
	String url = WEIXIN_MASS_MESSAGE_PREVIEW_LINK + "?access_token=" + accessToken;
	return WeixinInterfaceHelper.post(url, msgMap, MassReturnCode.class);
}
 
Example 9
Project: CreeperHostGui   File: SipEndPoint.java   View Source Code Vote up 5 votes
public void requestExtendedInfo(EnumSIPValues... values) throws IOException {
    
    Socket socket = new Socket(this.address.getAddress(), this.address.getPort());
    try {
        socket.setSoTimeout(5000);
        
        //Setup json:
        List<String> toRequest = new ArrayList<String>();
        for (EnumSIPValues value : values) {
            toRequest.add(value.toString());
        }
        
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        String endString = gson.toJson(toRequest);
        
        PrintWriter os = new PrintWriter(socket.getOutputStream());
        os.write(endString + "\n");
        os.flush();
        
        //Now wait for data:
        BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        String json = "";
        while ((line = is.readLine()) != null) {
            json += line;
        }

        Type myTypeMap = new TypeToken<Map<String,Object>>(){}.getType();
        extendedValues = gson.fromJson(json, myTypeMap);
    } finally {
        socket.close();
    }
}
 
Example 10
Project: africastalking-android   File: PaymentService.java   View Source Code Vote up 5 votes
private HashMap<String, Object> makeB2BRequest(String product, Business recipient) {
    HashMap<String, Object> body = new HashMap<>();
    body.put("username", username);
    body.put("productName", product);

    //
    Gson gson = new Gson();
    String json = gson.toJson(recipient);
    HashMap map = gson.fromJson(json, HashMap.class);
    body.putAll(map);

    return body;
}
 
Example 11
Project: full-javaee-app   File: Candidates.java   View Source Code Vote up 5 votes
public void setAccountOrigin(AccountOrigin accountOrigin) {
    if (accountOrigin != null) {
        Gson gson = new Gson();
        String json = gson.toJson(accountOrigin);
        setAccountOrigin(json);
    }
}
 
Example 12
Project: YiZhi   File: SpUtils.java   View Source Code Vote up 5 votes
/**
 * 保存List
 *
 * @param key      sp key值
 * @param datalist list
 * @param <T>      item 类型
 */
public static <T> void setDataList(String key, List<T> datalist) {
    if (null == datalist || datalist.size() <= 0)
        return;

    Gson gson = new Gson();
    //转换成json数据,再保存
    String strJson = gson.toJson(datalist);
    SpUtils.putString(AppUtils.getContext(), key, strJson);
}
 
Example 13
Project: SpringBoot_Wechat_Sell   File: JsonUtil.java   View Source Code Vote up 4 votes
public static String toJson(Object object) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();
    return gson.toJson(object);
}
 
Example 14
Project: SIIEScanner   File: Jsoner.java   View Source Code Vote up 4 votes
public String parse(){
    Gson gson = gsonInstance();
    return gson.toJson( this );
}
 
Example 15
Project: sendinblue-java-mvn   File: Sendinblue.java   View Source Code Vote up 4 votes
public String create_update_user(Object data) {
    Gson gson = new Gson();
    String json = gson.toJson(data);
    return post("user/createdituser", json);
}
 
Example 16
Project: sendinblue-java-mvn   File: Sendinblue.java   View Source Code Vote up 4 votes
public String campaign_recipients_export(Map<String, Object> data) {
    String id = data.get("id").toString();
    Gson gson = new Gson();
    String json = gson.toJson(data);
    return post("campaign/" + id + "/recipients", json);
}
 
Example 17
Project: JInOne   File: JsonData.java   View Source Code Vote up 4 votes
@Override
public String toString() {
    Gson gson=new GsonBuilder().serializeNulls().create();
    String json = gson.toJson(this);
    return json;
}
 
Example 18
Project: bridgefy-android-samples   File: Tweet.java   View Source Code Vote up 4 votes
public HashMap<String, Object> toHashMap() {
    Gson gson = new Gson();
    String s = gson.toJson(this);
    Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
    return gson.fromJson(s, type);
}
 
Example 19
Project: testing_security_development_enterprise_systems   File: ConverterImpl.java   View Source Code Vote up 3 votes
@Override
public String toJSon(T obj) {

    //see https://github.com/google/gson

    Gson gson = new Gson();
    String json = gson.toJson(obj);

    return json;
}
 
Example 20
Project: Yidu   File: TopAction.java   View Source Code Vote up 2 votes
/**
 * 获取排行榜名字的JSON数据
 * 
 * @return 排行榜名字的JSON数据
 */
public String getTopNameJsonData() {
    Gson gson = new Gson();
    return gson.toJson(YiDuConstants.TOP_NAME_MAP, Map.class);
}