parse json java result null - java

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

Related

Append text field data to an existing JSON file in java

I have a text field where user can enter data, once data is received i want to append it to existing JSON file.
I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem.
Error:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $
Below code :
JSON File :
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Text field value : String test ="3689";
so it should be appended as :
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Filereadwrite class :
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new
FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
linststring= new ArrayList();
// loop array
JSONArray msg = (JSONArray) jsonObject.get("vins");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
linststring.add(Vinno_Read);
}
String list_string = "";
System.out.println(linststring);
for(String temp:linststring){
list_string += temp;
System.out.println("amar1"+list_string);
}
System.out.println("amar"+list_string);
Vin vin4 = new Vin();
vin4.setVin("76354273462");
Vins vins = new Vins();
vins.addVins(vin4);
Gson gson = new Gson();
//String jsonValue=list_string;
String jsonValue = gson.toJson(list_string).toString();
System.out.println("json--"+jsonValue);
Vins vins1 = gson.fromJson(jsonValue, Vins.class);
System.out.println("ddd"+vins1);
Vin vin = new Vin();
vin.setVin("544554");
vins1.addVins(vin);
jsonValue = gson.toJson(vins1).toString();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json"));
writer.write(jsonValue);
System.out.println("Test"+jsonValue);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Setter Getter classes :
public class Vin {
#Expose
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
}
public class Vins {
#Expose
List<Vin> vins = new ArrayList<>();
public List<Vin> getVins() {
return vins;
}
public void addVins(Vin vin) {
this.vins.add(vin);
}
}
Main Logic:
you can see 4 blocks in the code
Reading the json file and parsing to a java Object
Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements
Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes)
Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file.
Input:
{"vins":[{"vin":"544554"},{"vin":"54554"}]}
Output:
{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}
Code
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
public class JSONFIlewrite {
public static String Vinno_Read;
public static List<String> linststring;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println(jsonObject);
linststring = new ArrayList<String>();
// loop array
JsonArray msg = (JsonArray) jsonObject.get("vins");
Iterator<JsonElement> iterator = msg.iterator();
while (iterator.hasNext()) {
Vinno_Read = iterator.next().toString();
System.out.println("Vinno_Read---->" + Vinno_Read);
}
Vin newVin = new Vin();
newVin.setVin("3689");
Gson gson = new Gson();
String json = gson.toJson(newVin);
System.out.println("json---->" + json);
FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Vins vins = new Vins();
while (iterator.hasNext()) {
vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class));
}
vins.addVin(newVin);
gson.toJson(vins, Vins.class, jw);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Notes:
Since I don't know what library you are using, I have updated the class names to be compatible to GSON.
I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)
To keep the existing content and append the new content to the end of JSON file:
Example1:
new FileWriter(file,true);
or you can try example02:
FileWriter file= new FileWriter(JSONLPATH,true)

Splitting String into object fields

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

How to change JsonObject in JsonArray?

I'm using javax.json and when I tried change jsonObject in my jsonArray:
String jsonString = "[{\"name\":\"xyz\"," +
"\"URL\":\"http://example.com\"}]";
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonArray jsonArray = jsonReader.readArray();
String jsonNewString = "{\"name\":\"zyx\","
+ "\"URL\":\"http://example2.com\"}]";
jsonReader = Json.createReader(new StringReader(jsonNewString));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
jsonArray.remove(0);
jsonArray.add(0, jsonObject);
I got this exception:
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
I also tried: jsonArray.set(0, jsonObject);, and got the same UnsupportedOperationException.
The javadoc of JsonArray states
JsonArray represents an immutable JSON array (an ordered sequence of
zero or more values). It also provides an unmodifiable list view of
the values in the array.
You can't change it. Create a new one with the value(s) you want.
JsonObject and JsonArray are immutable so you cannot modify the object , you can use this example and try to inspire from it :
creation of a new JsonObject who contains the same values and add some elements to it ..
Example :
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
public class Jsonizer {
public static void main(String[] args) {
try {
String s = "{\"persons\": [ {\"name\":\"oussama\",\"age\":\"30\"}, {\"name\":\"amine\",\"age\":\"25\"} ]}";
InputStream is = new ByteArrayInputStream(s.getBytes());
JsonReader jr = Json.createReader(is);
JsonObject jo = jr.readObject();
System.out.println("Before :");
System.out.println(jo);
JsonArray ja = jo.getJsonArray("persons");
InputStream targetStream = new ByteArrayInputStream("{\"name\":\"sami\",\"age\":\"50\"}".getBytes());
jr = Json.createReader(targetStream);
JsonObject newJo = jr.readObject();
JsonArrayBuilder jsonArraybuilder = Json.createArrayBuilder();
jsonArraybuilder.add(newJo);
for (JsonValue jValue : ja) {
jsonArraybuilder.add(jValue);
}
ja = jsonArraybuilder.build();
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("persons", ja);
JsonObject jsonAfterAdd = jsonObjectBuilder.build();
System.out.println("After");
System.out.println(jsonAfterAdd.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output :
Before :
{"persons":[{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
After
{"persons":[{"name":"sami","age":"50"},{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}

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

How to convert a Java Object to a JSONObject?

i need to convert a POJO to a JSONObject (org.json.JSONObject)
I know how to convert it to a file:
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(file.toString()), registrationData);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I dont want a file this time.
If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.
SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
The example below was pretty much lifted from mkyongs tutorial. Instead of saving to a file you can just use the String json as a json representation of your POJO.
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
YourObject obj = new YourOBject();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);
}
}
Here is an easy way to convert Java object to JSON Object (not Json String)
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.parser.JSONParser;
JSONObject jsonObject = (JSONObject) JSONValue.parse(new ObjectMapper().writeValueAsString(JavaObject));
How to get JsonElement from Object:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
final ObjectMapper objectMapper = new ObjectMapper();
final Gson gson = new Gson();
String json = objectMapper.writeValueAsString(source);
JsonElement result = gson.fromJson(json, JsonElement.class);

Categories