I have a txt file. It contains all json's. below is the sample data..
{"userid": "0be57386-b081-41fc-b5c4-98103956371f","segments":["2_GMC_L"]}{"userid": "57f2f319-ed9b-4dc9-a550-70b51b724acb","segments":["2_GMC_L"]}
{"userid": "ba009949-f658-4abe-a707-d2b460ee2046","segments":["2_GMC_L"]}
I have to get the whole data one json by json.. as a string values. and print...
Use JSONParser class for parsing JSONString, find below sample code.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"/Users/Jiten/Documents/file1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
String author = (String) jsonObject.get("author");
JSONArray companyList = (JSONArray) jsonObject.get("companyList");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
System.out.println("\nCompany List:");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
Related
For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.
I'm trying to write multiple times on a JSON file using JSON-Simple and Java, but I have some problems after the second run. I'm new to JSON so that's just a way to learn about it, here is the code:
public class Writer{
#SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
JSONParser parser = new JSONParser();
JSONObject outer = new JSONObject();
JSONObject inner = new JSONObject();
JSONObject data = new JSONObject();
ArrayList<JSONObject> arr = new ArrayList<JSONObject>();
inner.put("Name", "Andrea");
inner.put("Email", "andrea#mail.com");
arr.add(inner);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
File file = new File("temp.json");
if(file.exists()) {
PrintWriter write = new PrintWriter(new FileWriter(file));
Iterator<JSONObject> iterator = arr.iterator();
while(iterator.hasNext()) {
JSONObject it = iterator.next();
data = (JSONObject) it;
}
arr.add(data);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
write.write(outer.toString());
write.flush();
write.close();
} else {
PrintWriter write = new PrintWriter(new FileWriter(file));
write.write(outer.toString());
write.flush();
write.close();
}
}
}
So, I just wanna try to add the same thing without losing what I added before, but when I run:
The first run goes well, it prints normally on the file.
Result:
Dati: {"Clienti":[{"Email":"andrea#gmail.com","Nome":"Andrea"}]}
The second run too, it adds another field inside the list, keeping the first one too.
Result:
Dati:
{"Clienti":[{"Email":"andrea#gmail.com","Nome":"Andrea"},{"Email":"andrea#gmail.com","Nome":"Andrea"}]}
From the third run it doesn't upload anymore the file, instead of adding another field to the existent 2 it just prints the second result.
I tried many options but still can't understand how to add a third field without losing the previous two, how can i solve this?
Solved putting this on if clause:
if(file.exists()) {
Object obj = parser.parse(new FileReader("temp.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("Clienti");
PrintWriter write = new PrintWriter(new FileWriter(file));
Iterator<JSONObject> iterator = array.iterator();
while(iterator.hasNext()) {
JSONObject it = iterator.next();
data = (JSONObject) it;
System.out.println("Data" + data);
arr.add(data);
}
arr.add(inner);
System.out.println(arr);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
write.write(outer.toString());
write.flush();
write.close();
}
I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");
your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java
if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck
In Spring mvc I have a mytable.json file.
I want to fetch that json file data and then want to add to model.addAttribute().
mytable.json
{"name1":["place1.1","place1.2"],
"name2":["place2.1","place1.2"]
...........
.........}
I want to fetch the names with their corresponding citylist.
Ex:
name1=place1.1,place1.2
so,I have done:--
try {
JSONParser parser = new JSONParser();
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/mytable.json").getFile());
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
Iterator<String> keys = obj.values().iterator();
while( keys.hasNext() )
{
String key = (String)keys.next();
if ( obj.get(key) instanceof JSONObject )
{
model.addAttribute("key", key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
But I am getting error:
Unexpected character (�) at position 0.
in this line :
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
why??Where is the problem?
The JSONParser parser = new JSONParser(); is expecting a JSON String, not a .json file. hence the Unexpected character.... error.
You can InputStreamReader:
jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("file/mytable.json")));
I am returning a json from my class:
#POST("/test")
#PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream" and parse it to see if key1 exists:
String output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
output=output.toString();
JSONObject jsonObj = new JSONObject();
jsonObj.put("output", output);
if (jsonObj.get("output") != null){
**//search for key1 in output**
System.out.println("key1 exists");
}else{
System.out.println("key1 doesnt exist");
}
reader.close();
How can I convert output to JSONObject and search for "key1"?
I tried following but I got errors after arrows:
JSONObject jObject = new JSONObject(output); ---> The constructor JSONObject(String) is undefined
JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
And then you can verify the existence of the field using:
jsonObject.has("key1");
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples