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) {...}
Related
I'm trying to parse json file in my java project using this below code,
JSONParser parser = new JSONParser();
try {
Object obj = null;
try {
obj = parser.parse(new FileReader(new File("json/branch_list.json")));
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
System.out.println("Branches are :");
JSONArray listOfBranches = (JSONArray) jsonObject.get("branch_list");
Iterator iterator = listOfBranches.iterator();
for (int i = 0; i < listOfBranches.size(); i++) {
JSONObject c = listOfBranches.getJSONObject(i);
System.out.println("Branch are :" + listOfBranches.get(i));
}
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
From above code when i'm using this two below lines
JSONObject c = listOfBranches.getJSONObject(i);
String branchName = c.getString("branch_name");
Its shows the method getJSONObject(int) is undefined for the type JSONArray
And I'm getting the whole object when using this below code,
System.out.println("Branch are :"+listOfBranches.get(i));
It prints like this,
{"branch_name":"AMM"}
from this I want to get branch name using the key "branch_name". But I could not able to do this because of "the method getJSONObject(int) is undefined for the type JSONArray" exception
And I have added json-simple jar in my project. Could you please suggest me any idea to do this? Thanks in advance.
If i undestood you right then:
JSONObject item = (JSONObject)listOfBranches.get(0);
String branchName = (String)item.get("branch_name");
i think you should use org.json instead of simple-json. The method getJSONObject(i) is available in org.json. Refer to the below url for more detail.
https://stackoverflow.com/questions/2591098/how-to-parse-json
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/.
i'm fetching Json data in java, and my Json have different structure and not always the same. Example :
{"0":{"id"="255",name="example"},"1":{"news_id":"47221","news_infos":{"title":"test","date":"2014-05-14 17:44:02","shared":"47"},"website":"test.it"},"3":{"id"="55885",name="foo"}}
This is just an example. What i want to know is how i can skip the second one, we suppose the second one is a JsonArray.
This is an example of what I'm doing in java ;
for (int i = 0; i < jObj.length() ; i++) {
try {
JSONObject obj = jObj.getJSONObject(i); //Suppose that every entry in the Json is an object and not a JsonArray.
if (!obj.isNull("titrenews")) {
Home home = new Home();
Log.i("Infos","Yes");
home.setNomC(obj.getString("titrenews"));
home.setPhotoAr(photoNews);
home.setText(obj.getString("textnews"));
home.setNbrSick(obj.getString("sicks"));
homeList.add(home);
}
}catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
To sum up the problem i have a json data. composed of JsonObject and JsonArray, and what i want is to skip the jsonArray entry and avoid it
so any solutions please !
Try this approach:
for (Object obj : jObj) {
if (obj instanceof JSONObject){
//do something
}
else if (obj instanceof JSONArray){
continue;//skip
}
}
I'm working in my Twitch IRC Bot and we got a Problem.
We receive alot of information through the twitch API (json) like Who followed, dateOf .. viewercounts.. amount of followers and stuff like that.
Were making a Follow-Function to read all the names out of the whole list and set all into our database. First off we tried to just read all and system.output them but we always get the error: org.json.JSONException: JSONArray[100] not found.
We noticed that "0" is holding an array as well so we set the loop to 0-99 and it should change the link then by adding 100+ (next site) and read the JSON again. then it should just continue the loop with the next site.
Below is the Main code as well for the read-methods.
We tried debugging but we wasn't able to find a solution yet x(
MyBot Main Code Snippet:
JSONObject follower = null;
String followername = null;
int listnumber;
offsetvalue = 0;
for(int i = 0; i < TwitchStatus.totalfollows; i++) {
try {
follower = TwitchStatus.followerarray.getJSONObject(i);
} catch (JSONException e2) {
e2.printStackTrace();
}
try {
followername = follower.getJSONObject("user").getString("display_name");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("array ist: "+i +" " +followername);
listnumber = offsetvalue+99; // 0+99
if (i == listnumber){
offsetvalue = offsetvalue+100;
try {
TwitchStatus.FollowerTicker();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
// System.out.println("Follower abgleichs-Liste: "+followername);
}
And there is the Reader Method:
////////////////////////////////////////////////////////////////////////////////////
// Twitch Follower Ticker
////////////////////////////////////////////////////////////////////////////////////
private String readAll4(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl4(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll4(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void FollowerTicker() throws IOException, JSONException {
json = readJsonFromUrl2("https://api.twitch.tv/kraken/channels/dotastarladder_en/follows?direction=DESC&limit=100&offset="+MyBot.offsetvalue+"");
followerarray = json.getJSONArray("follows");
{
JSONObject follower = followerarray.getJSONObject(0);
neuerfollower = follower.getString("created_at");
fname = follower.getJSONObject("user").getString("display_name");
totalfollows = json.getInt("_total");
}
}
Note from the API docs:
limit optional integer Maximum number of objects in array. Default is 25. Maximum is 100.
So, what do you do? Query the next one, of course! Here's the bit of JSON from the linked page, and an example next URL. Basically, you just put an offset in, but the URL already declares it, so...
{
"_total": 1234,
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user1/follows?direction=DESC&limit=25&offset=25",
How I would solve this problem is something like this:
Create an AsyncTask that takes in the URL to parse the JSON text.
When the data has been received, start a new task to read the next one.
Read everything received in this JSON string
Compile everything after it has been downloaded as needed.
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"));