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;
}
Related
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) {...}
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/.
This is my method
public String buildJsonData(String username , String message)
{
JsonObject jsonObject = Json.createObjectBuilder().add("Username",username+":"+message).build();
StringWriter stringWriter = new StringWriter();
try(JsonWriter jsonWriter = Json.createWriter(stringWriter))
{
jsonWriter.write(jsonObject);
}
catch(Exception e)
{
System.out.print("buildJsonData ="+e);
}
return stringWriter.toString();
}
If i input username as john and message as hello.I get output as
{"Username":"john:hello"}
But I want output without braces and doublequotes I want my output as
John:hello
I tried to split it using array[0] but didn't get the output.Is it possible in json to get my desired output(without braces and quotes).
On the sending end, you would put the Username and Message entities into a JSONObject and send the resulting string over the network.
On the receiving end, you would unmarshal the JSON to extract the entities. You can then format them however you like.
Please read about JSON encoding here.
This is a simple example:
private String getResponse(){
JSONObject json = new JSONObject();
try {
json.put("Username", "John");
json.put("Message", "Hellow");
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
private void receiver(){
try {
JSONObject response = new JSONObject(getResponse());
String username = response.getString("Username");
String message = response.getString("Message");
System.out.println(String.format("%s : %s", username,message));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your structure is not really JSON.
A json structure would be like
{
Username : "John",
Message : "Hello"
}
Anf if your want to really use JSON, there is not way to remove braces and quotes. This IS Json.
If you want to output only the part you quoted, store the json value in a variable
String myoutput = stringWriter.toString();
And then remove the parts you don't want with replace() or a regexp
Braces are part of the JSON notation - they indicate an object. If you remove them, then it's not JSON any more. Same goes for double quotes.You are creating your JSON object as:
Json.createObjectBuilder().add("Username",username+":"+message)
This creates an object with property named Username and value john:hello. Again, this is the JSON notation. It's not intended to be read directly, but to facilitate data transfer between applications (on the same or different devices).
If all you want to create is john:message, then instead of creating a JSON object, you should simply do:
String result = username + ":" + message;
return result;
I have a very simple parser splitting string:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Parser {
public static void main(String args[]){
String newLog = new String();
try {
BufferedReader reader = new BufferedReader(new FileReader("/Users/John/IdeaProjects/tomcatParser/src/log.log"));
try {
while ((newLog = reader.readLine()) != null){
System.out.println(newLog.split("\\s"));
//System.out.println(newLog.split(" "));
break;
}
//reader.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
As you can see, I've got absolutely simple code, but as the result i see :
[Ljava.lang.String;#1aa8c488
What am I doing wrong?
You try to print an array object: this will not print the array members, but the array reference.
One solution: surround with Arrays.asList(), ie:
System.out.println(Arrays.asList(newLog.split("\\s")));
(better solution: use Arrays.toString() as suggested by the other answers. You learn something new every day.)
That's what you get when you try to print an array directly. It uses the toString method of the Object class which prints out the name of the class, the at-sign character and the unsigned hexadecimal representation of the hash code of the object. You get the "identity" of the array rather than a textual representation of its contents.
Instead, use:
System.out.println(Arrays.toString(newLog.split("\\s")));
System.out.println works with string. When you are passing object that is not string its method toString() is called automatically and you see the result of this call.
You are calling System.out.println with array argument and this is how toString() of arrays work. To see better output use
System.out.println(Arrays.toString(newLog.split("\\s")))
Method String.split(String regEx) return array of strings (String[]).
When you try to System.out.println any Object in Java it calls this object toString() method. toString() method for array returns exectly is what you see.
Use System.out.println(Arrays.toString(newLog.split("\\s"))); instead.
instead of :
while ((newLog = reader.readLine()) != null){
System.out.println(newLog.split("\\s"));
//System.out.println(newLog.split(" "));
break;
}
your code should be:
while ((newLog = reader.readLine()) != null){
String [] columns = newLog.split("\\s");
for (String result : columns) {
System.out.print(result);
}
break;
}
I have a function which fetches a certain website's HTML code. Eventually that function will return the whole page as an array. I am trying to save the page in another array, but it will always throw an exception (ArrayIndexOutOfBoundsException) for some reason.
I am not sure if I am just missing something elementary or if it's more than just that. To give you some of my code:
protected String[] doInBackground(String... login)
{
String[] page = new String[1024];
try {
page = executeHttpGet(); //THIS IS WHERE IT FAILS
} catch (Exception e) {
page[0] = "Error";
}
return page;
}
public String[] executeHttpGet() throws Exception {
URL u;
InputStream is = null;
DataInputStream dis;
String s;
int i = 0;
String[] page = new String[1024];
addSecurityException();
Authenticator.setDefault(new MyAuthenticator(activity));
try {
u = new URL("https://myurl.com");
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null) {
if (s.toString().length() > 10)
{
page[i] = s.toString();
i++;
}
}
} catch (IOException ioe) {
}
finally {
try {
is.close();
} catch (IOException ioe) {
}
}
return page;
}
}
Does anyone have any ideas why I am not able to assign the returned array to the array in doInBackground()? Help would be greatly appreciated.
Your catch-blocks are empty, which is a terrible idea, because you'll get no information when something goes wrong.
You don't need to initialize page on its declaraton, when you re-assign it two lines below (you'll have to change the catch-block to create a new array, 'though).
Have you checked that your URL doesn't return more than 1024 lines?
You don't need s.toString() when s is a String, because it will just return s.
When analyzing an exception, you should look at the whole stacktrace to find out where exactly the problem occurs.
When asking about an exception you should post the whole stacktrace!
When you have an unspecified number of elements List is a more flexible and easier-to-use alternative to arrays. Generally speaking, arrays are quite low-level and there's barely a reason to use them directly (they are very useful for building List implementations).