Json Parse Failed- javafx - json

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

Related

parsing Json in Android Studio when result is empty

I try to load datas from a Json that is on my server to my smartphone.
When the json is like this, it works and i get the label "spanishguitar":
{"file": "image.jpg", "objects": [{"bbox": [611, 82, 1231, 1265], "label": "spanishguitar", "prob": 0.991}]}
Here is my code:
public void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
instrumentname = jsonResult.objects.get(0).label;
But sometimes the json is empty like this:
{"file": "image.jpg", "objects": []}
So my plan is that if objects == null to get something like:
Toast.makeText(getApplicationContext(), "Uuuups, itś empty", Toast.LENGTH_SHORT).show();
Do you know how to parse the json, so that i get a message in the case of an empty "objects"?
Thank you!
Now it works. Here is my code:
#RequiresApi(api = Build.VERSION_CODES.N)
private void empty() throws IOException {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(String.valueOf(json));
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if (objects == null || objects.size() == 0) {
/////////////
runOnUiThread(new Runnable() {
#Override
public void run() {
noResult.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Identification failed", Toast.LENGTH_SHORT).show();
}});
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
} else {
updateLabel();
}
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
Thank you a lot for your help!
'Empty' is not 'null'.You can use
ArrayUtils.isEmpty(objects)
or
objects == null || objects.length() == 0
to detect whether you got an empty objects.
I writed a demo for you:
import com.google.gson.*;
public class Main
{
public static void main(String[] args)
{
JsonParser parser = new JsonParser();
// JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": []}");
JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": [{\"bbox\": [611, 82, 1231, 1265], \"label\": \"spanishguitar\", \"prob\": 0.991}]}");
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if(objects == null || objects.size() == 0) {
System.out.println("objects is empty");
}else{
JsonObject firstObj = objects.get(0).getAsJsonObject();
System.out.println("objects[0].label="+firstObj.get("label"));
}
}
}

Export all ElasticSearch data to JSON file

I need t export all data in the ElasticSearch and reindex all those data.
The export Java code as follows.
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
String scrollid = response.getScrollId();
try {
//把导出的结果以JSON的格式写到文件里
BufferedWriter out = new BufferedWriter(new FileWriter("es", true));
while (true) {
SearchResponse response2 = client.prepareSearchScroll(scrollid)
.setScroll(new TimeValue(1000000))
.execute().actionGet();
SearchHits searchHit = response2.getHits();
//再次查询不到数据时跳出循环
if (searchHit.getHits().length == 0) {
break;
}
System.out.println("查询数量 :" + searchHit.getHits().length);
for (int i = 0; i < searchHit.getHits().length; i++) {
String json = searchHit.getHits()[i].getSourceAsString();
out.write(json);
out.write("\r\n");
}
}
System.out.println("查询结束");
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The numbers of documents is about 140W. Use this java code 60W documents can be exported and throw an exception.
远程主机强迫关闭了一个现有的连接
You have to use the scrollid from the previous response for your next request.
See https://www.elastic.co/guide/en/elasticsearch/reference/1.7/search-request-scroll.html#scroll-scan for more details
Perhaps you can try something like this instead?
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
int sequence = 0;
do
{
response = client.prepareSearchScroll(response.getScrollId())
.setScroll(new TimeValue(600000))
.execute().actionGet();
if (response.getHits().getHits().length > 0)
{
try
{
final BufferedWriter out = new BufferedWriter(new FileWriter("es-" + (++sequence) , true));
for (final SearchHit hit : response.getHits().getHits())
{
out.write(hit.getSourceAsString());
out.write("\r\n");
}
out.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
while (response.getHits().hits().length > 0);

how to read a json file by hashMap in java

I have a very simple question. I want to read a json file by hashMap in java.
For example I have a json file like this:
{
"list": [
{
"ID" : "#12354667",
"value" : "data1."
}
{
"ID" : "#12345789",
"value" : "data2"
}
And whenever I call the id it returns the value. I have written this but I do not know how to read the file. Any help?
Thanks,
private JsonReader() throws IOException {
//readfile?
this.messages = new HashMap<String, String>();
}
public String getValue(final String ID)
{
if (this.messages.containsKey(ID))
{
return this.messages.get(value);
}
return "";
}
You can use JSONParser and FileReader to read your file into your Application. I'm not quite sure if this is what you searched for, but you can try it. You only have to give your ID to this method.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\yourFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray list= (JSONArray) jsonObject.get("list");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String id= (String) jsonObject.get("ID");
if(id.equals(hereYourFinalString ID)){
String value = (String) jsonObject.get("value");
System.out.println(value);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}

Blackberry how to get Json Response (java)

I want to get a JSON response on the simulator. How can I read JSON from the server?
public void run()
{
HttpConnection httpConn;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://example.com/login.php");
if (connDesc != null)
{
try {
httpConn = (HttpConnection)connDesc.getConnection();
final int iResponseCode = httpConn.getResponseCode();
Dialog.alert("Type: "+httpConn.getType());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
HttpConnection connection = (HttpConnection)Connector.open(urlConection);
InputStream inputStream = connection.openInputStream();
if(connection.getResponseCode() == HttpConnection.HTTP_OK){
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int readCharacter;
StringBuffer responseBuffer = new StringBuffer();
while ((readCharacter = reader.read()) != -1) {
responseBuffer.append((char) readCharacter);
connection.close();
inputStream.close();
reader.close();
String responseMessage = new String(responseBuffer);
}
}
You need to create JSONObject for the response.
try {
JSONObject object = new JSONObject(responseMessage);
} catch (JSONException e) {
e.printStackTrace();
}

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help