Splitting String into object fields - java

I looking for best aproach for this problem.
String example:
{"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
I need to create new object with gets fields values from the string. What is correct way to do it? Creating constructor and pass this string as parameter and use stringtokenizer inside it? Or maybe using Pattern would be better?

(I am going to correct the code)
I am proposing to use org.json.simple.*. In my opinion, it will be easy, for example:
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "....";
/*
* {"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Related

JSON (simple) parsing of file returns null values

It's my first time working with a JSON file, so I went with simple JSON library. Here's what works:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ParseCardJSON {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
Object obj;
try {
obj = parser.parse(new FileReader("C:\\Users\\owner\\Desktop\\A\\programming\\workspace\\MTG\\AllSets.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(obj.toString());
String name = (String) jsonObject.get("name");
String color = (String) jsonObject.get("power");
System.out.println("Name: " + name);
System.out.println("color: " + color);
} catch (Exception e) {
e.printStackTrace();
}
}
}
So the System.out.println(obj.toString()); prints out what I'm expecting:
({"LEA":{"name":"Limited Edition Alpha","code":"LEA","gathererCode":"1E","magicCardsInfoCode":"al","releaseDate":"1993-08-05","..)...
but the "name" and "color" prinlns are null. Any idea what could be wrong?
This happen because the name property is not in the root.
In fact you have a LEA key that is in the root, and the value of that property is another Object, that contains the following keys : name, code, gathererCode, magicCardsInfoCode, etc...
So if you want extract the name property, you need to do something like this
JSONObject object = (JSONObject) jsonObject.get("LEA");
String name = (String) object.get("name");
This should fix the problem.

How do I read from JSON File in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I've read some other questions about this, but they did not seem to help me.
As the title says, I want to know how to read from .json files using Java.
Eg. I want my program to read a boolean value. (That is what I want it to.)
I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed.
What I've found so far (That did not work):
String str = "Name";
JSONObject obj = new JSONObject();
String n = (String) obj.get("Name");
if (!n.equals("true")) {
} else
if (n.equals("true")) {
ButtonsShow = true;
} else if (n.equals("false")) {
ButtonsShow = false;
}
Click to view the .Json file
you try it:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

error: non-static method get(Object) cannot be referenced from a static context

The code below shows:
JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context
JSONArray cars = (JSONArray) JSONObject.get("cars");
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) JSONObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Anyone has any idea why this is the case?
(by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.)
Project: Code from StackOverflow page How to read json file into java with simple JSON library
Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line
JSONArray cars = (JSONArray) JSONObject.get("cars");
change it with
JSONArray cars = (JSONArray) person.get("cars");
Issue was since you are calling the get method directly on the class.

How to parse large local JSON file to retrieve player names and more with an array

I have a large stream of data that I can capture from a game that I play using CharlesProxy. I'd like to parse the data and have it print out (eventually build an excel spreadsheet) the player names, x and y location, and the guild name.
The JSON data in Paste-Bin (you'll have to go down a few entries to see one of the results that actually returns a player name as well):
http://pastebin.com/v4kAaspn
Here's an example I found here that I tried to use to just return the player name, but I get a Null Pointer Exception error. Any advice will be greatly appreciated, thank you so much!
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ToolMain {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"//Users//Brandon//Desktop//JSONData.JSON"));
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
//System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
//System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
//System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
Iterator<JSONObject> iterator = hexesArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = iterator.next();
String playerName = (String) factObj.get("player_name");
if (playerName != null) {
System.out.println(playerName);
}
}
//System.out.println(hexesArray);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The NullPointerException is happening on below line because your JSONArray msg is null:
Iterator<JSONObject> iterator = msg.iterator();
Apply a check if(msg is not null) before you create an iterator on it.
Try it this way:
JSONObject jsonObject = (JSONObject) obj;
//get responses
JSONArray rsp = (JSONArray)jsonObject.get("responses");
System.out.println(rsp);
//get return value
JSONObject rtvalue = (JSONObject)rsp.get(0);
System.out.println(rtvalue);
//get hexes object
JSONObject hexes = (JSONObject)rtvalue.get("return_value");
System.out.println(hexes);
//get hexes array
JSONArray hexesArray = (JSONArray)hexes.get("hexes");
System.out.println(hexesArray);

parse json java result null

I am stucking with parse json in java. Here is my code:
package url.process;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class jsonArray implements JSONAware{
private long l;
public jsonArray(long l){
this.l=l;
}
public long getArray(){
return l;
}
public void setArray(long l){this.l=l;}
#Override
public String toJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\""+getArray()+"\"");
sb.append("}");
return sb.toString();
}
public static void main(String[] args){
// doc doi tuong thanh chuoi
List <jsonArray> listjsonarray = new ArrayList<jsonArray>(){
{
add( new jsonArray(76543456));
add( new jsonArray(112233445));
add( new jsonArray(546372));
add( new jsonArray(9876553));
}
};
System.out.println(JSONArray.toJSONString(listjsonarray));
//doc chuoi thanh doi tuong
String jsonString = "[{\"76543456\"},"+"{\"112233445\"},"+"{\"546372\"},"+"{\"9876553\"}]";
try{
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonString);
for(int i =0;i<jsonArray.size();i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
long l = Long.parseLong((String) jsonObject.get("l"));
jsonArray ja = new jsonArray(l);
System.out.println("Elements is "+ja.getArray());
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
The result is :
[{"76543456"},{"112233445"},{"546372"},{"9876553"}]
null
I do not know to parse this array above. Please help me, thank you so much and have a good time.
The null output is because of
}catch(Exception e){
System.out.println(e.getMessage());
});
The json is not valid and therefore you get a ParseException and this exception has no message.
As I can see you want to get the l property of the JSONObject
long l = Long.parseLong((String) jsonObject.get("l"));
in this case the correct json would be
String jsonString = "[{\"l\": \"76543456\"},"+"{\"l\": \"112233445\"},"+"{\"l\": \"546372\"},"+"{\"l\": \"9876553\"}]";
Your JSON is invalid. Braces {} indicate a JSON object which contains key-value pairs. But you are putting JSON strings in them.
[{"76543456"},{"112233445"},{"546372"},{"9876553"}]
Perhaps you meant to have
["76543456","112233445","546372","9876553"]
The JSON format is described here.
You'll have other problems later when trying to cast a String to a JSONObject. Handle those appropriately. If you're storing JSON strings, you should get back Java String objects.
JSON is a key value data structure. For example, a JSON object is as follow:
{"name" : "John Smith"}
The string you input there doesn't follow the convention of JSON, therefore the program couldn't work

Categories