how to read a json file by hashMap in java - json

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();
}
}

Related

pretty print Json with Spring boot, only works with console

I have this code,
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(strJson); //works fine here
return strJson; //return it doesn't display pretty on browser
Any idea how to fix this? I've been trying all the solution here on the internet and especially stackoverflow and none of it works.
If you want clear view, it's from my previous code
I use thymeleaf html again,
#Controller
#RequestMapping("/menu")
public class DataController {
// load json
private List<DataModel> theDatawiz;
private String strJson = null;
#PostConstruct
private void loadData() {
// load json
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// setup array mapper
ObjectMapper objectMapper = new ObjectMapper();
DataModel[] datawiz = null;
try {
datawiz = objectMapper.readValue(strJson, DataModel[].class);
} catch (Exception e) {
e.printStackTrace();
}
// create the list
theDatawiz = new ArrayList<>();
for(int i = 0; i < datawiz.length; i++) {
DataModel dat = new DataModel(datawiz[i].getId(),datawiz[i].getName());
theDatawiz.add(dat);
}
}
// add mapping for "/list"
#GetMapping("/list")
public String listMenu(Model theModel) {
// add to the spring model
theModel.addAttribute("thelist", theDatawiz);
return "menu-list";
}
// add mapping for "/list"
#GetMapping("/jason")
public String printJson(Model theModel) {
// add to the spring model
theModel.addAttribute("result", strJson);
return "jason";
}
}
On the jason.html,
<p th:text="'JSON: ' + ${result}" style="white-space: pre"></p>

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"));
}
}
}

java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference

Every time I open my app it crashes because of this error I dont know what should I do please help me... I have also attached logcat screen shot below and the java class in which the error is comming.
DataParser.java:
public class DataParser {
private HashMap<String,String> getPlace(JSONObject googlePlacesJson){
HashMap<String,String> googlePlaceMap=new HashMap<>();
String placeName="-NA-";
String vicinity="-NA-";
String latitude="";
String logitude="";
String reference="";
List<HashMap<String,String>> placesList=new ArrayList<>();
try {
if(!googlePlacesJson.isNull("name")){
placeName=googlePlacesJson.getString("name");
}
if (!googlePlacesJson.isNull("vicinity")){
vicinity=googlePlacesJson.getString("vicinity");
}
latitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
logitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference=googlePlacesJson.getString("reference");
googlePlaceMap.put("name",placeName);
googlePlaceMap.put("vicinity",vicinity);
googlePlaceMap.put("lat",latitude);
googlePlaceMap.put("lng",logitude);
googlePlaceMap.put("reference",reference);
} catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;
}
private List<HashMap<String,String>> getPlaces(JSONArray jsonArray){
long count;
count=jsonArray.length(); // error comes on this line
List<HashMap<String,String>> placesList=new ArrayList<>();
HashMap<String,String> placeMap=null;
for(int i=0;i<count;i++){
try {
placeMap=getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}
this is the screen shot my my log cat:
The problem is somewhere in here:
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results"); // !!! this line here !!!
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
getJSONArray("results"); returns null and that's causing problems later (NullPointerException).
What you should do:
Check your JSON for syntax errors.
Place a breakpoint at the getJSONArray() line and take a look at jsonData and jsonObject if everything is, as it should be.
The array you want to retrieve is probably not valid or not in the jsonData at all.
i would start by validating if the jsonArray is null before running the entire method. or:
if (jsonArray != null)
count=jsonArray.length();
else count = 0;
then debug to find out why you are calling that method with a null object.

Json Parse Failed- javafx

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??

Json parsing Using Volley does not get cahced

I Parse json using volley framework, which every time gets response from the server, does not check the cache, It has taken a whole day, Here is my code. Any of you have used volley for parsing json are expected to help
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(diag_url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
// handle data, like converting it to xml, json, bitmap etc.,
// Parsing json
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
try {
DiagRegPojo test = new DiagRegPojo();
JSONObject obj = jsonArray.getJSONObject(i);
String testName = obj.getString("content");
Log.d("Response From Cache", testName);
test.setTitle(testName);
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
// Creating volley request obj
JsonArrayRequest testReq = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DiagRegPojo test = new DiagRegPojo();
test.setTitle(obj.getString("content"));
Log.d("Response From Server", obj.getString("content"));
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(testReq);
}
}
To cache images, I have used this. sure it can be of some help to you.
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}