当前位置: 首页>>代码示例>>Java>>正文


Java JsonParser类代码示例

本文整理汇总了Java中com.google.gson.JsonParser的典型用法代码示例。如果您正苦于以下问题:Java JsonParser类的具体用法?Java JsonParser怎么用?Java JsonParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonParser类属于com.google.gson包,在下文中一共展示了JsonParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: formMessage

import com.google.gson.JsonParser; //导入依赖的package包/类
public String formMessage(String content) {
    try {
        JsonObject contentObj = new JsonParser().parse(content).getAsJsonObject();
        int userId = contentObj.get("uid").getAsInt();
        String datetime = contentObj.get("datetime").getAsString();
        SimpleDateFormat insdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        SimpleDateFormat outsdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String parsedDatetime = outsdf.format(insdf.parse(datetime));
        String chatContent = contentObj.get("content").getAsString();
        String username = userDao.getUserById(userId).getUsername();
        String avatar = userDao.getUserById(userId).getAvatar();

        JsonObject messageJson = new JsonObject();
        messageJson.addProperty("uid", userId);
        messageJson.addProperty("username", username);
        messageJson.addProperty("datetime", parsedDatetime);
        messageJson.addProperty("avatar", avatar);
        messageJson.addProperty("content", chatContent);
        return messageJson.toString();
    } catch (ParseException e) {
        e.printStackTrace();
        return "error";
    }
}
 
开发者ID:qinjr,项目名称:TeamNote,代码行数:25,代码来源:ConvertUtilImpl.java

示例2: matFromJson

import com.google.gson.JsonParser; //导入依赖的package包/类
public static Mat matFromJson(String json){
        JsonParser parser = new JsonParser();
        JsonObject JsonObject = parser.parse(json).getAsJsonObject();

        int rows = JsonObject.get("rows").getAsInt();
        int cols = JsonObject.get("cols").getAsInt();
        int type = JsonObject.get("type").getAsInt();

        String dataString = JsonObject.get("data").getAsString();       
        byte[] data = DatatypeConverter.parseBase64Binary(dataString);
//        byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT); 

        Mat mat = new Mat(rows, cols, type);
        mat.put(0, 0, data);

        return mat;
    }
 
开发者ID:fossasia,项目名称:zooracle,代码行数:18,代码来源:OpenCVUtils.java

示例3: post

import com.google.gson.JsonParser; //导入依赖的package包/类
@Override
public String post(final HttpServletRequest req, final HttpServletResponse res) {
	try {
		final String payload = req.getParameter("payload");
		final JsonParser jsonParser = new JsonParser();
		final JsonObject json = jsonParser.parse(payload).getAsJsonObject();

		final Map<String, String[]> params = req.getParameterMap();

		slackReceiveHandler.handleAction(json, params);
	} catch (final Exception e) {
		handleException(e);
	}

	return "";
}
 
开发者ID:nitroventures,项目名称:bot4j,代码行数:17,代码来源:SlackActionWebhookImpl.java

示例4: downloadNote

import com.google.gson.JsonParser; //导入依赖的package包/类
public File downloadNote(int noteId, String type, String leftPath)throws IOException, DocumentException {
    Note note = noteDao.getNoteById(noteId);
    String currentVersion = note.getHistory().get(note.getVersionPointer());
    JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject();
    String content = obj.get("content").getAsString();
    String htmlPath = leftPath + "htmlTemp.html";
    File file = new File(htmlPath);
    file.createNewFile();
    FileWriter writer = new FileWriter(file);
    writer.write("<body>" + content + "</body>");
    writer.close();
    if(type.equals("pdf")) {
        String pdfPath = leftPath + "pdfTemp.pdf";
        File pdfFile = new File(pdfPath);
        exportUtil.htmlToPdf(htmlPath, pdfFile);
        file.delete();
        file = pdfFile;
    }
    //default html
    return file;

}
 
开发者ID:qinjr,项目名称:TeamNote,代码行数:23,代码来源:DownloadServiceImpl.java

示例5: convertJSONToWeatherObj

import com.google.gson.JsonParser; //导入依赖的package包/类
public static Weather convertJSONToWeatherObj(String jsonString) {
    Weather weatherObj = new Weather();

    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(jsonString).getAsJsonObject();

    weatherObj.setTemperature(new Temperature(Temperature.Unit.KELVIN,
            Double.parseDouble(json.getAsJsonObject("main").get("temp").toString())));

    for (int index = 0; index < json.getAsJsonArray("weather").size(); index++) {
        JsonObject object = json.getAsJsonArray("weather").get(index).getAsJsonObject();
        weatherObj.getCondition().add(
                weatherCodes.getConditionFromCode(Integer.parseInt(object.get("id").toString())));
        weatherObj.setIcon(fileLoad.loadImageFromService(object.get("icon").getAsString()));
    }
    return weatherObj;
}
 
开发者ID:ykarim,项目名称:WeatherWatch,代码行数:18,代码来源:DataFormat.java

示例6: Configuration

import com.google.gson.JsonParser; //导入依赖的package包/类
public Configuration(final File file) {

        this.file = file;
        String cont = null;
        this.jsonParser = new JsonParser();

        try {
            if (file.exists()) {
                cont = new BufferedReader(new FileReader(this.file)).lines().collect(Collectors.joining("\n"));
                //cont = IOUtils.toString(new BufferedInputStream(new FileInputStream(this.file)), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (cont == null || cont.equals("")) {
            cont = "{}";
        }
        json = jsonParser.parse(cont).getAsJsonObject();

    }
 
开发者ID:Rubicon-Bot,项目名称:Rubicon,代码行数:21,代码来源:Configuration.java

示例7: actionLoad

import com.google.gson.JsonParser; //导入依赖的package包/类
@FXML
private void actionLoad(ActionEvent event) {
    fileChooser.setTitle("Load Config");
    File file = fileChooser.showOpenDialog(paneConfig.getScene().getWindow());
    try {
        String config = FileUtils.readFileToString(file, "UTF-8");
        JsonElement json = new JsonParser().parse(config);
        wrapper.configure(json, null, null);
    } catch (IOException ex) {
        LOGGER.error("Failed to read file", ex);
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("failed to read file");
        alert.setContentText(ex.getLocalizedMessage());
        alert.showAndWait();
    }
}
 
开发者ID:hylkevds,项目名称:SensorThingsProcessor,代码行数:17,代码来源:FXMLController.java

示例8: assertFileInCache

import com.google.gson.JsonParser; //导入依赖的package包/类
private void assertFileInCache (File file,String key) throws IOException {
	 InputStream in = new FileInputStream(file);
	 try {
		Reader reader = new InputStreamReader(in);
		String text = CharStreams.toString(reader);
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(text);
		JsonObject jsonCache = je.getAsJsonObject();
		JsonElement elt = jsonCache.get(key);
		JsonObject generatedObj = elt.getAsJsonObject();
		boolean generated = generatedObj.get("generated").getAsBoolean();
		assertTrue("Test not generated", generated);
	} finally {
		if (in!=null) in.close();
	}
}
 
开发者ID:gw4e,项目名称:gw4e.project,代码行数:17,代码来源:GW4EProjectTestCase.java

示例9: testSerialization

import com.google.gson.JsonParser; //导入依赖的package包/类
@Test
public void testSerialization() {
    Gson gson = getGSON(getFactory(t -> "foo", emptyList(), emptyList()));
    SubTypeA typeA = new SubTypeA();
    typeA.foo = 1;
    typeA.bar = "t1";
    typeA.baz = "t2";

    JsonElement actual = gson.toJsonTree(typeA, new TypeToken<Base>() { }.getType());
    JsonElement expected = new JsonParser().parse(makeJSON(1, "t1", "t2"));
    Assert.assertEquals(actual, expected);

    SubTypeB typeB = new SubTypeB();
    typeB.foo = 2;
    typeB.bar = "t2";
    typeB.qux = asList("a", "b");

    actual = gson.toJsonTree(typeB, new TypeToken<Base>() { }.getType());
    expected = new JsonParser().parse(makeJSON(2, "t2", asList("a", "b")));
    Assert.assertEquals(actual, expected);
}
 
开发者ID:yahoo,项目名称:bullet-core,代码行数:22,代码来源:FieldTypeAdapterFactoryTest.java

示例10: testTrainString

import com.google.gson.JsonParser; //导入依赖的package包/类
/**
 * Test train string.
 */
@Test
@Ignore // only run train test if necessary. This is an expensive process.
public void testTrainString() {

	if (checkConnection()) {
		JsonParser parser = new JsonParser();
		Object obj;
		try {
			obj = parser.parse(new FileReader("src/test/resources/training.json"));
			JsonObject jsonObject = (JsonObject) obj;
			System.out.println(jsonObject.toString());
			RasaService.sendTrainRequest(jsonObject.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	checkConnection();
	assert (true);
}
 
开发者ID:BotMill,项目名称:rasa-botmill-plugin,代码行数:25,代码来源:RasaBotMillServiceTest.java

示例11: downloadNotebook

import com.google.gson.JsonParser; //导入依赖的package包/类
public File downloadNotebook(int notebookId, String type, String leftPath) throws IOException,DocumentException{
    File tempDir = new File(leftPath + "tempDir");
    String tempPath = leftPath + "tempDir/";
    tempDir.mkdirs();
    ArrayList<Integer> notes = notebookDao.getNotebookById(notebookId).getNotes();
    for(int noteId : notes){
        Note note = noteDao.getNoteById(noteId);
        String currentVersion = note.getHistory().get(note.getVersionPointer());
        JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject();
        String content = obj.get("content").getAsString();
        String htmlPath = tempPath + noteId +".html";
        File file = new File(htmlPath);
        file.createNewFile();
        FileWriter writer = new FileWriter(file);
        writer.write("<body>" + content + "</body>");
        writer.close();
        if(type.equals("pdf")) {
            String pdfPath = tempPath + noteId +".pdf";
            File pdfFile = new File(pdfPath);
            exportUtil.htmlToPdf(htmlPath, pdfFile);
            file.delete();
        }
    }
    return exportUtil.compressExe(tempDir, leftPath + "temp.zip");
}
 
开发者ID:qinjr,项目名称:TeamNote,代码行数:26,代码来源:DownloadServiceImpl.java

示例12: getWeiXinMessage

import com.google.gson.JsonParser; //导入依赖的package包/类
/**
 * 根据code获取微信token和openid
 *
 * @param code
 * @return
 */
public static JsonObject getWeiXinMessage(String code) throws Exception {
    JsonParser parser = new JsonParser();
    logger.info("wechat code:" + code);
    String toGetToken = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=" + SSOCommon.weixinAppKey +
            "&secret=" + SSOCommon.weixinAppSecret +
            "&code=" + code +
            "&grant_type=authorization_code";
    logger.info(toGetToken);
    String tokeContent = HttpHelper.getInstance().get(toGetToken);        //access token
    logger.info(tokeContent);
    JsonObject object = null;        //取得token和openid
    if (tokeContent != null) {
        object = parser.parse(tokeContent).getAsJsonObject();
        if (object.get("errcode") != null) {
            throw new Exception("访问微信出现异常");
        }
    }
    return object;
}
 
开发者ID:Zephery,项目名称:newblog,代码行数:27,代码来源:SSOUtil.java

示例13: recognizeImagePath

import com.google.gson.JsonParser; //导入依赖的package包/类
public String recognizeImagePath(String imageUrl) throws Exception {
    String filePath = urltoImagePath(imageUrl);
    HashMap<String, String> options = new HashMap<>();
    options.put("detect_direction", "true");
    options.put("probability", "true");
    String str = client.basicGeneral(filePath, options).toString();
    logger.info("返回的文本:" + str);
    JsonParser parser = new JsonParser();
    JsonObject object = parser.parse(str).getAsJsonObject();
    try {
        return object.get("words_result").getAsJsonArray().get(0).getAsJsonObject().get("words").getAsString();
    } catch (Exception e) {
        logger.error("", e);
        throw new Exception();
    } finally {
        FileUtils.deleteQuietly(new File(filePath));
    }
}
 
开发者ID:Zephery,项目名称:newblog,代码行数:19,代码来源:WordRecognition.java

示例14: validate

import com.google.gson.JsonParser; //导入依赖的package包/类
public static Collection<String> validate(String json, Collection<String> requiredFields) throws InvalidJson {
    if (json == null) {
        throw new InvalidJson("Null JSON object");
    }
    try {
        ArrayList<String> missing = new ArrayList<>();
        JsonParser parser = new JsonParser();
        JsonObject root = parser.parse(json).getAsJsonObject();
        for (String field : requiredFields) {
            if (!root.has(field)) {
                missing.add(field);
            }
        }
        return missing;
    } catch (JsonSyntaxException e) {
        throw new InvalidJson("Malformed JSON: " + json);
    }
}
 
开发者ID:kszatan,项目名称:gocd-phabricator-staging-material,代码行数:19,代码来源:GsonService.java

示例15: run

import com.google.gson.JsonParser; //导入依赖的package包/类
@Override
public void run()
{
    String json = "";
    try {
        Scanner sc = new Scanner(new URL(streamLink).openStream());
        StringBuilder sb = new StringBuilder();
        while(sc.hasNextLine())
            sb.append(sc.nextLine());
        json = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println(json);

    JsonObject jsonData = new JsonParser().parse(json).getAsJsonObject();
    JsonObject stream = jsonData.get("stream").getAsJsonObject();
    Twitchy.isLive = stream != null;
    if(stream != null)
    {
        Twitchy.streamGame = getJsonString(stream.get("game"), "");
        Twitchy.streamViewers = getJsonInt(stream.get("viewers"), 0);
        Twitchy.streamTitle = getJsonString(stream.get("channel").getAsJsonObject().get("status"), "");
    }
}
 
开发者ID:OCDiary,项目名称:Twitchy,代码行数:27,代码来源:TCCheck.java


注:本文中的com.google.gson.JsonParser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。