I have a question about my error code. I am working on a project with Angular, Java, Spark and an SQL database.
The method contains a prepared statement with an SQL Select statement. In the whileloop wants to go through as long as a result is found. Pack the queried data into a Json object, and these Json objects into a Json array.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import finanzplanpackage.connection.ConnectionConfiguration;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.String;
import java.util.logging.Level;
import java.util.logging.Logger;
public class n_paresmodul {
private ConnectionConfiguration c = new ConnectionConfiguration();
public String viewdata() {
String data = "";
JsonArray ja = new JsonArray();
try{
PreparedStatement pre = c.getconn().prepareStatement("SELECT * FROM n_pares");
ResultSet res = pre.executeQuery();
while (res.next()) {
JsonObject jo = new JsonObject();
jo.put("account_id", res.getInt("account_id"));
jo.put("mandant_id", res.getInt("mandant_id"));
jo.put("id", res.getInt("id"));
jo.put("sourcedata", res.getString("sourcedata"));
ja.add(jo);
}
data = ja.toString();
} catch(
SQLException ex)
{
Logger.getLogger(n_paresmodul.class.getName()).log(Level.SEVERE, null, ex);
}
return data;
}
When compiling, the compiler throws me the following error message.
symbol: method put (java. lang. String, int)
location: variable jo of type com. google. gson.JsonObject
enter image description here
Can someone please help me and tell me what I'm doing wrong with the put-method?
thank you
com.google.gson.JsonObject does not have any method put()
You should try using addProperty("account_id", res.getInt("account_id"))
Related
I have nested JSON with bunch of children objects, but I just need response_time and question, subquestions of survey_data. What is the best way to parse nested JSON in rest controller to the object in spring?
{
"is_test_data":false,
"language":"English",
"url_variables":{
"requestId":{
"key":"requestId",
"value":"1"
}
},
"response_time":1114,
"survey_data":{
"2":{
"id":2,
"type":"parent",
"question":"For each of the following factors, please rate your recent project",
"subquestions":{
"10":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Overall Quality : Rating",
"answer":null,
}
},
"11":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Achievement of Intended Objectives : Rating",
"answer":null
}
}
}
},
"33":{
"id":33,
"type":"HIDDEN",
"question":"Submitted",
"answer_id":0,
}
}
}
Thank you.
What you should do is parse the complete json to jsonObject using json-simple jar
which create a map like structure for the json and then you can simply get the desired value from it using the key as I explained in below example
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonDeserializer {
public static void main(String[] args) throws Exception {
File file = new File("test.json");
InputStream is = new FileInputStream(file);
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
String jsonTxt = textBuilder.toString();
Object obj = new JSONParser().parse(jsonTxt);
JSONObject jo = (JSONObject) obj;
System.out.println(jo.get("response_time"));
}
}
JSON is a data communication format that is lightweight, text-based. Objects and arrays are two structured kinds that JSON can represent. A JSONArray may extract text from a String and convert it to a vector-like object. The getString(index) method of JSONArray can be used to parse a nested JSON object. This is a helper method for the getJSONString method (index). The getString() method returns a string.
I'm new with Java Azure Functions.
I get Service Bus Trigger and Azure SQL output working, but need now advice with parsing json message.
I have Service Bus trigger, which provides data like "{ "name": "John","city": "NYC"}"
I would like to store this to Azure SQL. How to parse JSON and store to SQL?
package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
//import java.sql.ResultSet;
/**
* Azure Functions with Azure Storage Queue trigger.
*/
public class TopicTriggerSQLOutput {
/**
* This function will be invoked when a new message is received at the specified path. The
message contents are provided as input to this function.
*/
#FunctionName("TopicTriggerSQLOutput")
public void run(
#ServiceBusTopicTrigger(
name = "message",
topicName = "newtopic",
subscriptionName = "newsubscription",
connection = "topicconnstring"
) String message,
final ExecutionContext context
) {
String connectionUrl = "jdbc:sqlserver:...database.windows.net;loginTimeout=30;";
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
context.getLogger().info("SeviceBus message" + message); // I get JSON returned
correctly here.
// How to parse message json string?
// Create and execute a SELECT SQL statement.
String InsertSql = "INSERT INTO [dbo].[Target_Table] ([NAME],[CITY]) VALUES
('NameString', 'CityString')";
// insert the data
statement.executeUpdate(InsertSql);
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
context.getLogger().info("Message: " + message);
}
}
Problem solved with importing Gson. https://www.tutorialspoint.com/gson/gson_first_application.htm
import com.google.gson.Gson;
Student myjson = gson.fromJson(jsonString, myjson.class);
How is arbitrary JSON converted to arbitrary XML using BaseX?
I'm looking at JsonParser from BaseX for this specific solution.
In this case, I have tweets using Twitter4J:
package twitterBaseX;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import main.LoadProps;
import org.basex.core.BaseXException;
import twitter4j.JSONException;
import twitter4j.JSONObject;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterObjectFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterOps {
private static final Logger log = Logger.getLogger(TwitterOps.class.getName());
public TwitterOps() {
}
private TwitterFactory configTwitterFactory() throws IOException {
LoadProps loadTwitterProps = new LoadProps("twitter");
Properties properties = loadTwitterProps.loadProperties();
log.fine(properties.toString());
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true)
.setJSONStoreEnabled(true)
.setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
.setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
.setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
.setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));
return new TwitterFactory(configurationBuilder.build());
}
public List<JSONObject> getTweets() throws TwitterException, IOException, JSONException {
Twitter twitter = configTwitterFactory().getInstance();
Query query = new Query("lizardbill");
QueryResult result = twitter.search(query);
String string = null;
JSONObject tweet = null;
List<JSONObject> tweets = new ArrayList<>();
for (Status status : result.getTweets()) {
tweet = jsonOps(status);
tweets.add(tweet);
}
return tweets;
}
private JSONObject jsonOps(Status status) throws JSONException, BaseXException {
String string = TwitterObjectFactory.getRawJSON(status);
JSONObject json = new JSONObject(string);
String language = json.getString("lang");
log.fine(language);
return json;
}
}
The JSONObject from Twitter4J cannot just get jammed into XML?
There are a number of online converters which purport to accomplish this, and, which, at least at first glance, seem quite adequate.
see also:
Converting JSON to XML in Java
Java implementation of JSON to XML conversion
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc for more information
I am trying to write an arraylist string list to a file. The arraylist string is actually a string converted from twitter JSON and I am trying to write the tweet text into the file.
However, I keep getting this error:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at kr.ac.uos.datamining.test.main(test.java:32)
The code for the whole class are below:
package kr.ac.uos.datamining;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.uos.datamining.JSONParser;
import kr.ac.uos.datamining.Tweet;
import kr.ac.uos.datamining.User;
public class test {
public static List <String> list = new ArrayList<String>();
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException, SQLException {
JSONParser j = new JSONParser(new File("D:/curl-7.32.0/samsunggalaxy-01-23-2014.txt"));
ArrayList<Tweet> tweets = j.getTweets();
for(Tweet tweet : tweets){
list.add(tweet.getText());
}
FileWriter writer = new FileWriter("D:/samsunggalaxy.txt");
for (String tweet: list) {
Line 32 writer.write(tweet);
}
writer.close();
}
}
Since it is said as Unknown Source, is it the problem with the String tweet: list line?
I tried to change it to String str: list but its not working as well
The only way that you got a NullPoineterException is that your text is null, so validate what you want to write before writing it.
for (String tweet: list) {
if(tweet != null || !tweet.equals("")) {
writer.write(tweet);
}
}
Seems one of your tweet objects is null. This is the problem here.
It seems the String tweet is null, so I'd check your Tweet.getText() method to ensure it never returns null.
I am using the recent Solr 4.2.1 solrj libraries.
I am trying to execute an MLT Query from a java program. It works fine as long as I only provide small chunks in the stream.body, but that kind of defeats my purpose.
When I try to use the ContentStream I don't get a response back, when I do the solr.query, it makes another request.
It looks like the server is getting my solr.request() ok. Appreciate any pointers.
Oh, and I am talking to a solr 3.6.1
Here is what I have so far:
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.util.ClientUtils;
public class SolrJSearcher {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
ModifiableSolrParams params = new ModifiableSolrParams();
String mltv[] = {"Big bunch of text for testing - redacted for brevity"};
String dvalues[] = {"mlt"};
String svalues[] = {"0"};
ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/mlt");
ContentStream cs = new ContentStreamBase.StringStream(mltv[0]);
up.addContentStream( cs);
SolrQuery theQuery = new SolrQuery();;
theQuery.set("qt", dvalues);
up.setParam("start", "0");
try {
solr.request(up);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
QueryResponse response = solr.query(theQuery);
SolrDocumentList results = response.getResults();
for (int i = 0; i < results.size(); ++i) {
System.out.println(results.get(i));
}
}
}
As far as I know, MoreLikeThis is meant to find documents similar to a document already in the index. If you're searching documents similar to an input string, then just insert a temporary item in your index before you do the query, and remove it afterwards.
I've been using the following successfully:
/*
* Build up a MoreLikeThis query to retrieve documents
* similar to the one with id originalId
*/
private SolrQuery buildUpMoreLikeThisQuery(String field3, String originalId) {
SolrQuery query = new SolrQuery();
query.setQueryType("/" + MoreLikeThisParams.MLT);
query.set(MoreLikeThisParams.MATCH_INCLUDE, true);
query.set(MoreLikeThisParams.MIN_DOC_FREQ, 1);
query.set(MoreLikeThisParams.MIN_TERM_FREQ, 1);
query.set(MoreLikeThisParams.MIN_WORD_LEN, 7);
query.set(MoreLikeThisParams.BOOST, false);
query.set(MoreLikeThisParams.MAX_QUERY_TERMS, 1000);
query.set(MoreLikeThisParams.SIMILARITY_FIELDS,
"field1,field2");
query.setQuery("id:" + originalId);
query.set("fl", "id,score");
query.addFilterQuery("field3:" + field3);
int maxResults = 20;
query.setRows(maxResults);
return query;
}