本文整理汇总了Java中com.ibm.json.java.JSONObject.parse方法的典型用法代码示例。如果您正苦于以下问题:Java JSONObject.parse方法的具体用法?Java JSONObject.parse怎么用?Java JSONObject.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.ibm.json.java.JSONObject
的用法示例。
在下文中一共展示了JSONObject.parse方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getNLUOutput
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
* Invoke NLU to extract keywords (entities)
*
* @param text Text document from which personal data needs to be extracted
* @return response.toString() NLU output as a String
*/
private JSONObject getNLUOutput(String text) throws Exception {
try {
Map<String, String> nluCreds = getNLUCredentials();
// String user = System.getenv("username");
// String password = System.getenv("password");
String model = System.getenv("wks_model");
// if (logger.isInfoEnabled()) {
// logger.info("NLU Instance details");
// logger.info("user: " + user + ", modelid: " + model + " For password, refer env variables");
// }
NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27, nluCreds.get("username"), nluCreds.get("password"));
EntitiesOptions entitiesOptions = new EntitiesOptions.Builder().model(model).emotion(true).sentiment(true)
.limit(20).build();
KeywordsOptions keywordsOptions = new KeywordsOptions.Builder().emotion(true).sentiment(true).limit(20)
.build();
Features features = new Features.Builder().entities(entitiesOptions).keywords(keywordsOptions).build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder().text(text).features(features).build();
AnalysisResults response = service.analyze(parameters).execute();
return JSONObject.parse(response.toString());
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
示例2: getNLUCredentials
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
private Map<String, String> getNLUCredentials() throws Exception{
Map<String, String> nluCredentialsMap = new HashMap<String, String>();
try{
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
//String VCAP_SERVICES = "{\"natural-language-understanding\":[{\"credentials\":{\"url\":\"https://gateway.watsonplatform.net/natural-language-understanding/api\",\"username\":\"8ea86c6c-c681-4186-bf91-e766413145ad\",\"password\":\"XaQHFNhhpnKX\"},\"syslog_drain_url\":null,\"volume_mounts\":[],\"label\":\"natural-language-understanding\",\"provider\":null,\"plan\":\"free\",\"name\":\"NLU - GDPR\",\"tags\":[\"watson\",\"ibm_created\",\"ibm_dedicated_public\",\"lite\"]}]}";
if (VCAP_SERVICES != null) {
// parse the VCAP JSON structure
JSONObject obj = (JSONObject) JSONObject.parse(VCAP_SERVICES);
JSONArray nluArray = (JSONArray)obj.get("natural-language-understanding");
if( nluArray != null && nluArray.size() > 0 ){
for( int i = 0; i < nluArray.size(); i++ ){
JSONObject o = (JSONObject)nluArray.get(i);
if( o.get("credentials") != null ){
JSONObject credsObject = (JSONObject)o.get("credentials");
nluCredentialsMap.put("username", (String)credsObject.get("username"));
nluCredentialsMap.put("password", (String)credsObject.get("password"));
nluCredentialsMap.put("nluURL", (String)credsObject.get("url"));
}
}
}
}
}catch(Exception e){
e.printStackTrace();
throw new Exception(e.getMessage());
}
if( nluCredentialsMap.get("username") == null ){
throw new Exception("NLU Credentials not found");
}
return nluCredentialsMap;
}
示例3: getPersonalDataForViewer
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
* This method extracts personal data and scores those personal data.
* Output data is formatted so that it can be consumed by D3 tree viewer library
*
* @param payload Text document from which personal data needs to be extracted
* @return Response Personal data and score output as JSON
*/
@POST
@Path("/forviewer")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getPersonalDataForViewer(InputStream payload) {
try {
if (payload == null) {
logger.error("Input data not available");
return Response.serverError().entity("Input data not available").build();
}
JSONObject payloadJSON = JSONObject.parse(payload);
if(logger.isInfoEnabled()){
logger.info("Input text provided by user");
logger.info(payloadJSON.toString());
}
PIIDataExtractor piiExtractor = new PIIDataExtractor();
JSONObject response = piiExtractor.getPersonalDataForViewer(payloadJSON);
if(logger.isInfoEnabled()){
logger.info("Output for D3 viewer format");
logger.info(response.toString());
}
return Response.ok(response, MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.build();
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
示例4: getPersonalDataForConsumer
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
* This method extracts personal data and scores those personal data.
* Output data is more generic, targetted to be consumed by other applications
*
* @param payload Text document from which personal data needs to be extracted
* @return Response Personal data and score output as JSON
*/
@POST
@Path("/forconsumer")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getPersonalDataForConsumer(InputStream payload) {
try {
if (payload == null) {
return Response.serverError().entity("Input data not available").build();
}
JSONObject payloadJSON = JSONObject.parse(payload);
if(logger.isInfoEnabled()){
logger.info("Input text provided by user");
logger.info(payloadJSON.toString());
}
PIIDataExtractor piiDataExtractor = new PIIDataExtractor();
JSONObject response = piiDataExtractor.getPersonalDataInGenericFormat(payloadJSON);
if(logger.isInfoEnabled()){
logger.info("Output for consumer format");
logger.info(response.toString());
}
return Response.ok(response, MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.build();
} catch (Exception e) {
logger.error("Error: " + e.getMessage());
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
示例5: getRequestSchema
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
@Override
public JSONObject getRequestSchema() throws ServiceException {
String requestSchema = "{\"$schema\": \"http://json-schema.org/draft-04/schema#\",\"type\": \"object\",\"properties\": {\"input\": {\"type\": \"string\"}},\"required\": [\"input\"]}";
JSONObject schema;
try {
schema = JSONObject.parse(requestSchema);
} catch (IOException e){
throw new ServiceException();
}
return schema;
}
示例6: getResponseSchema
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
@Override
public JSONObject getResponseSchema() throws ServiceException {
String responseSchema = "{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"type\":\"object\",\"properties\":{\"date\":{\"type\":\"string\"},\"output\":{\"type\":\"string\"}},\"required\":[\"date\",\"output\"]}";
JSONObject schema;
try {
schema = JSONObject.parse(responseSchema);
} catch (IOException e){
throw new ServiceException();
}
return schema;
}
示例7: formatTraits
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
private static List<Map<String,String>> formatTraits(String profileJson){
List<Map<String,String>> arr = new ArrayList<Map<String,String>>();
try
{
JSONObject tree = JSONObject.parse(profileJson);
formatTree((JSONObject)tree.get("tree"), 0, arr);
} catch(Exception e) { e.printStackTrace(); }
return arr;
}
示例8: processControlPort
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
protected void processControlPort(StreamingInput<Tuple> stream, Tuple tuple) {
String jsonString = tuple.getString(0);
try {
JSONObject config = JSONObject.parse(jsonString);
Boolean shouldReloadModel = (Boolean)config.get("reloadModel");
if(shouldReloadModel) {
synchronized(model) {
model = loadModel(javaContext.sc(), modelPath);
}
}
} catch (Exception e) {
e.printStackTrace();
tracer.log(TraceLevel.ERROR, "TRACE_M_CONTROL_PORT_ERROR", new Object[]{e.getMessage()});
}
}
示例9: getResultAsJson
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
*
* @return the payload as a JSON Object
*/
protected JSONObject getResultAsJson() {
try {
return JSONObject.parse((String)result);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
示例10: CloudantCredential
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
public CloudantCredential () {
//Get VCAP_SERVICES environment varialbe from Bluemix - cloudant service should be bound to this service for
//environment variable to be present
//
//Alternatively - provide a manifest.yml where environment variables are provided
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
if (VCAP_SERVICES != null) {
try {
System.out.println("vcap is: " + VCAP_SERVICES);
JSONObject vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
JSONArray credentials = (JSONArray) vcap.get("cloudantNoSQLDB");
cloudantInstance = (JSONObject) credentials.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
//System.out.println(cloudantCredentials);
LOGGER.info("username is from VCAP_SERVICES: " + cloudantCredentials.get("username").toString());
LOGGER.info("password is from VCAP_SERVICES: " + (cloudantPassword == null ? "null" : "******"));
//System.out.println(cloudantCredentials.get("password"));
cloudantUsername = cloudantCredentials.get("username").toString();
cloudantPassword = cloudantCredentials.get("password").toString();
cloudantURI = cloudantCredentials.get("url").toString();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//VCAP services does not exist so look for dbUsername, dbPassword and dbURI environment variables
//When running locally - these environment variables need to be defined by user. Values should be
//from a Cloudant service running in Bluemix
cloudantUsername = System.getenv("dbUsername");
LOGGER.info("username is from environment variable dbUsername: " + cloudantUsername);
cloudantPassword = System.getenv("dbPassword");
LOGGER.info("password is from environment variable dbPassword: " + (cloudantPassword == null ? "null" : "*****"));
cloudantURI = System.getenv("dbURI");
}
}
示例11: json4j
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
public static JSONObject json4j(JsonObject object) throws IOException {
return JSONObject.parse(object.toString());
}
示例12: testContinuousAggregateLastSeconds
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
* Test a continuous aggregation.
*/
@Test
public void testContinuousAggregateLastSeconds() throws Exception {
// Uses JSON4J
assumeTrue(hasStreamsInstall());
final Topology t = newTopology();
TStream<String> source = t.periodicSource(new PeriodicStrings(), 100, TimeUnit.MILLISECONDS);
TStream<JSONObject> aggregate = source.last(3, TimeUnit.SECONDS).aggregate(new AggregateStrings());
TStream<String> strings = JSONStreams.serialize(aggregate);
Tester tester = t.getTester();
Condition<List<String>> contents = tester.stringContents(strings);
// 10 tuples per second, each is aggregated, so 15 seconds is around 150 tuples.
Condition<Long> ending = tester.atLeastTupleCount(strings, 150);
complete(tester, ending, 30, TimeUnit.SECONDS);
assertTrue(ending.valid());
long startTs = 0;
for (String output : contents.getResult()) {
JSONObject agg = JSONObject.parse(output);
JSONArray items = (JSONArray) agg.get("items");
long ts = (Long) agg.get("ts");
// Should see around 30 tuples per window, once we
// pass the first three seconds.
assertTrue("Number of tuples in window:" + items.size(), items.size() <= 45);
if (agg.containsKey("delta")) {
long delta = (Long) agg.get("delta");
assertTrue(delta >= 0);
if (startTs == 0) {
startTs = ts;
} else {
long diff = ts - startTs;
if (diff > 3000)
assertTrue(
"Number of tuples in window:" + items.size(),
items.size() >= 25);
}
}
}
}
示例13: testPeriodicAggregateLastSeconds
import com.ibm.json.java.JSONObject; //导入方法依赖的package包/类
/**
* Test a periodic aggregation.
*/
@Test
public void testPeriodicAggregateLastSeconds() throws Exception {
// Uses Condition.getResult
assumeTrue(!isStreamingAnalyticsRun());
final Topology t = newTopology();
TStream<String> source = t.periodicSource(new PeriodicStrings(), 100, TimeUnit.MILLISECONDS);
TStream<JSONObject> aggregate = source.last(3, TimeUnit.SECONDS).aggregate(
new AggregateStrings(), 1, TimeUnit.SECONDS);
TStream<String> strings = JSONStreams.serialize(aggregate);
Tester tester = t.getTester();
Condition<List<String>> contents = tester.stringContents(strings);
// 10 tuples per second, aggregate every second, so 15 seconds is around 15 tuples.
Condition<Long> ending = tester.atLeastTupleCount(strings, 15);
complete(tester, ending, 30, TimeUnit.SECONDS);
assertTrue(ending.valid());
long startTs = 0;
for (String output : contents.getResult()) {
JSONObject agg = JSONObject.parse(output);
JSONArray items = (JSONArray) agg.get("items");
long ts = (Long) agg.get("ts");
// Should see around 30 tuples per window, once we
// pass the first three seconds.
assertTrue("Number of tuples in window:" + items.size(), items.size() <= 45);
if (agg.containsKey("delta")) {
long delta = (Long) agg.get("delta");
assertTrue(delta >= 0);
assertTrue("timeBetweenAggs: " + delta, delta > 800 && delta < 1200);
if (startTs == 0) {
startTs = ts;
} else {
long diff = ts - startTs;
if (diff > 3000)
assertTrue(
"Number of tuples in window:" + items.size(),
items.size() >= 25);
}
}
}
}