Append text field data to an existing JSON file in java - 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)

Related

JSONObject["data"] not found in Test (Junit5) [duplicate]

I want to read this JSON file with java using json library
"ListeCar": [
{
"id": "R",
"size": "2",
"Orientation": "Horizontal",
"Position": {
"Row": "2",
"Column": "0"
}
}
This is my java code :
package rushhour;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.*;
public class JsonClass {
public static void main(String[] args) throws IOException, JSONException {
try{
JSONObject obj = new JSONObject(new FileReader("C:\\Users\\Nuno\\Desktop\\School\\clg-g41326\\RushHourJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray Liste = obj.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i <Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getString("Position");
System.out.println(Position);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}
I'm doing this in netbeans and it's kind a my first time using Json !
I want just to do a system.out from this little json code. I don't know why he's not finding the file that i put in the new JSONObjet ...
{
"ListeCar":[
{
"id":"R",
"size":"2",
"Orientation":"Horizontal",
"Position":{
"Row":"2",
"Column":"0"
}
}]
}
try placing this in your .json file
your json is not valid... try placing it in this site to check for it's validity.... http://json.parser.online.fr/
And the code for the correct output....
public static void main(String[] args) throws IOException, JSONException, ParseException {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/home/Desktop/temp.json"));
JSONObject objJsonObject = new JSONObject(obj.toString());
System.out.println(objJsonObject);
JSONArray Liste = objJsonObject.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i < Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getJSONObject("Position").toString();
System.out.println(Position);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You forgot to parse json... which is done in the above code.... a link about the tutorial on how to do this is as follows:: http://crunchify.com/how-to-read-json-object-from-file-in-java/

org.json.JSONException: JSONObject["ListeCar"] not found

I want to read this JSON file with java using json library
"ListeCar": [
{
"id": "R",
"size": "2",
"Orientation": "Horizontal",
"Position": {
"Row": "2",
"Column": "0"
}
}
This is my java code :
package rushhour;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.*;
public class JsonClass {
public static void main(String[] args) throws IOException, JSONException {
try{
JSONObject obj = new JSONObject(new FileReader("C:\\Users\\Nuno\\Desktop\\School\\clg-g41326\\RushHourJson.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray Liste = obj.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i <Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getString("Position");
System.out.println(Position);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}
I'm doing this in netbeans and it's kind a my first time using Json !
I want just to do a system.out from this little json code. I don't know why he's not finding the file that i put in the new JSONObjet ...
{
"ListeCar":[
{
"id":"R",
"size":"2",
"Orientation":"Horizontal",
"Position":{
"Row":"2",
"Column":"0"
}
}]
}
try placing this in your .json file
your json is not valid... try placing it in this site to check for it's validity.... http://json.parser.online.fr/
And the code for the correct output....
public static void main(String[] args) throws IOException, JSONException, ParseException {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/home/Desktop/temp.json"));
JSONObject objJsonObject = new JSONObject(obj.toString());
System.out.println(objJsonObject);
JSONArray Liste = objJsonObject.getJSONArray("ListeCar");
String listeCar = Liste.getJSONObject(0).getString("id");
for (int i = 0; i < Liste.length(); i++) {
String id = Liste.getJSONObject(i).getString("id");
System.out.println(id);
String size = Liste.getJSONObject(i).getString("size");
System.out.println(size);
String Orientation = Liste.getJSONObject(i).getString("Orientation");
System.out.println(Orientation);
String Position = Liste.getJSONObject(i).getJSONObject("Position").toString();
System.out.println(Position);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You forgot to parse json... which is done in the above code.... a link about the tutorial on how to do this is as follows:: http://crunchify.com/how-to-read-json-object-from-file-in-java/

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

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