I am trying to handle the json response, that is like
{"Status":true,"UserId":111,"FirstName":"dev","LastName":"dev","Gender":-1,"BirthdayDate":"0000-00-00","Phone":"","ProfilePicture":"","ProfilePicture60px":"","ProfilePicture120px":"","CountryId":-1,"Email":"droidwithmxxmail.com","Password":"******123","RegisterDate":"2015-05-08 20:08:07","SessionId":"fce248fe6499b7a9338a1b64554509eb77841"}
but getting org.json.JSONException: no value for exception
My code is this.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
allres =jsonObj.getJSONArray(jsonStr);
for (int i = 0; i < allres.length(); i++) {
JSONObject c = allres.getJSONObject(i);
userId = c.getString("UserId");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this code:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
userId = jsonObj.getString("UserId");
} catch (JSONException e) {
e.printStackTrace();
}
Your JSON string doesn't have an array in it, so the object that you will be getting from the first JSONObject is already where your information lives.
Related
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"));
}
}
}
pass the vehiclename object to another activity
and set that value as a text view
Please Help Me
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONObject object1 = response.getJSONObject("liveMapResponseVO");
JSONArray jsonArray = object1.getJSONArray("locations");
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("vehicleName"));
movie.setRating(jsonObject.getString("speed"));
movie.setGenre(jsonObject.getString("stopTime"));
movie.setYear(jsonObject.getString("idleTime"));
Log.d(TAG, jsonObject.getString("vehicleName"));
movieList.add(movie);
}
pDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
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);
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??
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();
}
}