How does the JSON Parser work exactly? - java

Ok so I have been given a project to build a TST(Completed) and am supposed to use JSON parser on a Dictionary file to load the values into my Data structure and was given a basic class of code for example. This is the very first Time I have ever been exposed to this utility and I have absolutely no idea on how it works. Typically when I want to parse an input i would simply do something along the lines of
String[] parse = txt.split("|");
yet this obviously isn't going to work, So In the end of the code I see where it differentiates (or i think it does anyways) The Key & The Value, I need to read those line by line to feed into a another method in which I would typically do with a for Loop yet have no clue as to what syntax this method even uses
for(int i = 0; i < JSON.Size; i++) {
first = get.JSON_Key(i);
last = get.JSON_Value(i);
tst.put(key, value);
}
So obviously that would be better suited pseudo code, I don't know if this is storing separate values in separate containers and if so what to use to get a hold of those values the following is the example code we were given
public class ReadJSON
{
public static void main( String[] args )
{
String infile = "dictionary.json";
JsonReader jsonReader;
JsonObject jobj = null;
try
{
jsonReader = Json.createReader( new FileReader(infile) );
// assumes the top level JSON entity is an "Object", i.e. a dictionary
jobj = jsonReader.readObject();
}
catch(FileNotFoundException e)
{
System.out.println("Could not find the file to read: ");
e.printStackTrace();
}
catch(JsonParsingException e)
{
System.out.println("There is a problem with the JSON syntax; could not parse: ");
e.printStackTrace();
}
catch(JsonException e)
{
System.out.println("Could not create a JSON object: ");
e.printStackTrace();
}
catch(IllegalStateException e)
{
System.out.println("JSON input was already read or the object was closed: ");
e.printStackTrace();
}
if( jobj == null )
return;
Iterator< Map.Entry<String,JsonValue> > it = jobj.entrySet().iterator();//Not sure what this is doing
Map.Entry<String,JsonValue> me = it.next();//not sure what this is doing
String word = me.getKey();
String definition = me.getValue().toString();
for(int i =0; i < jsonReader.; i++) {
}
}
}
Any help in understanding this a bit more and correct syntax for that for loop would be appreciated

The code is using JSR 353: Java API for JSON Processing. Look at the https://jsonp.java.net/.

Related

I am getting an ArrayIndexOutOfBoundsException with my code. Is this setup correctly?

I am using a .txt file that has data in it formatted the same way throughout.
For example:
title|format|onLoan|loanedTo|loanedOn
title|format|onLoan|loanedTo|loanedOn
title|format|onLoan|loanedTo|loanedOn
title|format|onLoan|loanedTo|loanedOn
I am opening the file and then trying to transfer that information into class object and then put that object in a arrayList of that class.
The problem I am having is with the age old ArrayIndexOutOfBoundsException. I am not sure what is causing it. It is probably something simple. Any guidance would be appreciated.
java.lang.ArrayIndexOutOfBoundsException: 1
at Library.open(Library.java:230)
Scanner input = null;
String mediaItemString = "";
MediaItem open = new MediaItem(); //class created for this object
String[] libraryItem;
//try catch block for exception handling
try {
input = new Scanner(new File("library.txt"));
while (input.hasNextLine()) {
mediaItemString = input.nextLine();
libraryItem = mediaItemString.split("\\|");
System.out.println(libraryItem[0].toString());
System.out.println(libraryItem[1].toString()); //error here, line 230
System.out.println(Boolean.parseBoolean(libraryItem[2].toString()));
System.out.println(libraryItem[3].toString());
System.out.println(libraryItem[4].toString());
open.setTitle(libraryItem[0].toString());
open.setFormat(libraryItem[1].toString());
open.setOnLoan(Boolean.parseBoolean(libraryItem[2].toString()));
open.setLoanedTo(libraryItem[3].toString());
open.setDateLoaned(libraryItem[4].toString());
items.add(open);
}
} catch (FileNotFoundException e){
System.out.println("There was an error with the file.");
} finally {
input.close();
}
Well I was hoping to split the string with delimiters and then assign those values to the MediaItem appropriately.
Make sure you don't have any missing value for a column. Also check for empty new lines.
It looks like some lines does not follow described format.
My suggection - add condition before array processing like
...
libraryItem = mediaItemString.split("\\|");
if(libraryItem.length <5) {
log.error("Error: libraryItem.length is {} for string {}", libraryItem.length, mediaItemString);
continue;
}
System.out.println(libraryItem[0].toString());
...

Building a JSONObject in Java without throwing an exception

Is there a way in Java to build a JSONObject without having to deal with an exception? Currently I'm using the default constructor, which however forces me to put try/catch blocks in the code. Since in the rest of the code I'm using the "opt" version of get, checking if the return value is null, is there a way to build the object in the same way? (that is, some kind of constructor that returns null if it can't build the json from a string).
Example:
try {
JSONObject temp = new JSONObject(someString);
} catch (JSONException e) {
e.printStackTrace();
}
What I would like to do:
JSONObject temp = ??????(someString);
if(temp != null) {...}
You need to create the method manually, as any parser will most probably throw one or the other Exception in case of any discrepancy.Try something like this:-
public JSONObject verifyJSON(String inputString){
JSONObject temp;
try {
temp = new JSONObject(inputString);
} catch (JSONException e) {
temp = null;
e.printStackTrace();
}
return temp;
}
Then you can do :-
JSONObject temp = verifyJSON(someString);
if(temp != null) {...}

"JSONArray initial value should be a string or collection or array" (twitter4j, twitterapi, JSONObject)

That is my first question here and for me. Please be advised: I searched this whole forum and I really got the feeling, I have overseen something! So I just ask for my "special" case.
I have a .json file, which is correct and starts with array (validated through jsonlint.com).
My code is:
public static void main(String[] args) throws IOException, ParseException, JSONException {
String inputPath = "/home/e/Desktop/";
FileReader br = new FileReader(inputPath + "Antikoerperyosi.json");
JSONArray array = new JSONArray(br);
try {
for(int index = 0; index < array.length(); ++index) {
JSONObject hashTag = array.getJSONObject(index);
System.out.println(hashTag);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I managed to read out a single .json and after correcting my files json syntax, I got really confused of how to tell to grab from the object "status" the object "entities" and then from object "entities" the array "hashtags".
I will append the first two lines of my JSON in hope it will make it easier to understand my point. (I could not attend, I a am new here)
JSON-File(snippet, I cannot intend if I am not mistaken..):
"status":{....."entities":{"urls":[],"hashtags":[{"indices":[35,44],"text":"LuxLeaks"},{"indices":[49,62],"text":"Handelsblatt"}],
next JSON[..."status":{.....}], etc.
Thanks a lot.

Java Method to Read JSON Elements

JSON is easy to use but sometime writing multiple child elements gives pain to write getJSONObject("") again and again in Java. Is there any simple way to avoid repetitive calls and have code more clean?
After trying multiple round i came up with below approach, You just pass JSON Object and all elements with "/" to below Java method and it will read JSON value. Note- This code is more for string value and you can customize it more based on your needs.
public static String getJSONTagValue(JSONObject partData, String xpath) {
String output="";
String[] getPrmString=xpath.split("/");
try {
if (partData.has(getPrmString[0])){
for (int i=0;i<getPrmString.length;i++){
if (partData.has(getPrmString[i]) && i!=getPrmString.length-1){
partData=partData.getJSONObject(getPrmString[i]);
} else if (partData.has(getPrmString[i])) {
output=partData.get(getPrmString[i])+"";
if (output.contains("xsi:nil")){
output="";
} else if (output.contains(".0")){
output=output.replace(".0", "");
}
}
}
}
if ("".equalsIgnoreCase(output)){
System.out.println("Missing xpath in Response ",xpath);
}
} catch (JSONException e) {
System.out.println("Missing xpath in Response ",xpath)
e.printStackTrace();
}
return output;
}

Convert Json Array to Java Array

I'm trying to convert this JSON string into an array:
{"result":"success","source":"chat","tag":null,"success":{"message":"%message%","time":%time%,"player":"%player%"}}
I would like to output it like this:
<%player%> %message%
I'm very new to java, I came from PHP where you could just do somthing along the lines of:
$result = json_decode($jsonfile, true);
echo "<".$result['success']['player']."> ".$result['success']['message'];
Output: <%player%> %message%
Is there an easy way to do this in java?
I searched for some similar topics but I didn't really understand them. Could someone explain this to me like I'm 5?
Why reinvent the wheel, use GSON - A Java library that can be used to convert Java Objects into their JSON representation and vice-versa
JSON-lib is a good library for JSON in Java.
String jsonString = "{message:'%message%',player:'%player%'}";
JSONObject obj = JSONObject.fromObject(jsonString);
System.out.println("<" + obj.get("message") + ">" + obj.get("player") );
You can also use xStream for doing it which has got a very simple API. Just Google for it.
You can always use the following libraries like:
- Jackson
- GSON
Ok here is the right way to do it Without using any library:
Eg:
JSONArray jarr = api.giveJsonArr();
// giveJsonArr() method is a custom method to give Json Array.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobj = jarr.getJSONObject(i); // Taking each Json Object
String mainText = new String(); // fields to hold extracted data
String provText = new String();
String couText = new String();
String fDatu = new String();
try {
mainText = jobj.getString("Overview"); // Getting the value of fields
System.out.println(mainText);
} catch (Exception ex) {
}
try {
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
} catch (Exception ex) {
}
try {
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
} catch (Exception ex) {
}
try {
String cloText = jobj.getString("ClosingDate");
fDatu = giveMeDate(cloText);
System.out.println(fDatu);
} catch (Exception ex) {
}
}
As you see you have many alternatives. Here is a simple one from json.org where you find lots of other alternatives. The one they supply them selves is simple. Here is your example:
String json = "{\"result\":\"success\",\"source\":\"chat\",\"tag\":null,\"success\":{\"message\":\"%message%\",\"time\":%time%,\"player\":\"%player%\"}}";
JSONObject obj = new JSONObject(json);
JSONObject success = obj.getJSONObject("success");
System.out.println("<" + success.get("player") + "> "
+ success.get("message"));

Categories