I've the following code, but when I am saving below JSON in database its giving me wrong url like {"#url#":"https:\/\/www.test.com\/test"}
import org.json.simple.JSONObject;
public class DemoURL {
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(msgJson.toString());
}
}
I want url like {"#url#":"https://www.test.com/test"}
Please suggest how to fix it?
Here is the solution:
public class App{
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(getCleanURL(msgJson.toString()));
}
private static String getCleanURL(String url){
return url.replaceAll("\\\\", "").trim();
}
}
This gives correct output, simply run this code. This will store exact value in the database.
{"#url#":"https://www.test.com/test"}
You are using org.json.simple JSON library. JSON-Simple escapes char from String.
You can't change this thing, as its not configurable.
But you can use org.json JSON library, this will not escape String, and good part is, you don't have to change your code, existing syntax will work fine.
e.g.
import org.json.JSONObject;
public class DemoURL {
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(msgJson.toString());
}
}
output : {"#url#":"https://www.test.com/test"}
Try replacing slash(/) with unicode character \u2215 before passing it to JSON object.
try to quote the string with single quotes, something like this
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", "\'"+url+"\'");
System.out.println(msgJson.toString());
Related
I have a very large JSON file in the following format:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
It looks like a JSONArray. All the records are written in the same line.
Can you help me how can I parse this file using Java. I want to read each JSON object and display all the fullname and ids. Below is my attempt, but my code is not working:
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONFileReaderDriver {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException
{
String filename="Aarau";
String src="C:\\"+filename+".json";
JSONParser parser = new JSONParser();
JSONObject obj;
try
{
BufferedReader br=new BufferedReader (new FileReader(src));
obj = (JSONObject) new JSONParser().parse(row);
String fullname=obj.get("fullname");
String id=obj.get("id");
System.out.println ("fullname: "+fullname+" id: "+id);
}catch(Exception e)
{e.printStackTrace();}
br.close();
}
}
Make your life easy and use an ObjectMapper.
This way you simply define a Pojo with the same properties as you json object.
In you case you need a Pojo that looks like this:
public class Person{
private String fullname;
private int id;
public Person(String fullname, int id) {
this.fullname = fullname;
this.id = id;
}
public String getFullname() {
return fullname;
}
public int getId() {
return id;
}
}
With that you only need to do:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
This is a hassle free and type safe approach.
Dependencies needed:
https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
you can use Json.simple java api , below is code that can helpful to you
byte[] bFile = Files.readAllBytes(new File("C:/xyz.json").toPath());
JSONArray root = (JSONArray) JSONValue.parseWithException(bFile);
JSONObject rootObj = (JSONObject) root.get(0);
You can get values from JSONObject based on key , it also depends on format of your json as there could be nested json data. So you have to extract data accordingly . Apart from this you can use jackson parser api or GSON as well.
Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.
try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);
for (int i=0;i<root.size();i++)
{
JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");
System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}
Your json is a JSONArray, so when you are parsing it, you need to parse it as a JSONArray.
JSONParser jsonParser = new JSONParser();
JSONArray a = (JSONArray) jsonParser.parse(new FileReader(src));
for (Object o : a) {
// access your object here.
}
I would suggest going with Jackson, in particular the Jackson Streaming API which is perfect for parsing large arrays like this.
See this answer: https://stackoverflow.com/a/24838392/3765428
I have been trying to execute this program, but it shows error saying that urlconnectionreader cannot be resolved. I'm new to programming. Can someone help me with this?
This is my code:
import java.net.*;
import java.io.*;
public class ReadTextFromUrl {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
// enter code here
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
There are Many Libraries to read text from URL,
You can Try jsoup library to read or extract only text.
import java.io.IOException;
import org.jsoup.Jsoup;
public class ReadTextFromURL {
public static void main(String[] args) throws IOException {
String text = Jsoup.connect("https://stackoverflow.com/questions/40741265/read-only-text-from-url-using-java").get().text();
System.out.println(text);
}
}
In your case the class name should be URLConnectionReader or you can change the the calling function via your class name .
String content = ReadTextFromUrl.getText(args[0]);
what you need to study more is objects.you must know that the classes are the blueprints.you cant use a saw blueprint to saw a tree.you need the saw itself.and by creating a object from that class you will have the saw.so when you have the saw in your hands you can saw the tree.making an object from a class works exactly the same.and using the ways(methods) to saw the tree with the actual saw is like using the methods of the class.
lets think you have a class named Saw and it has a method named sawTheTree.
public class Saw {
public void sawTheTree {
// do the sawing
}
}
its the blueprint by now.to use this saw and the method you need this :
Saw saw = new Saw();
now you have the saw in your hands.lets go and saw the tree.for this you need this code in your main method or where ever you feel the need of sawing the tree.
saw.sawTheTree();
now the the saw will saw the tree for you.
P.S: in your code you have declared the getText method static so you don't need the object creation part.if you are asking why look again at static statement description.but to use a non static method from a class you need to create the object.
I have a json string like this:
{"a":"vala", "b":"valb", "c":"valc"}
I want to convert the above string to a JSONObject so that I can do something like:
testObject.remove("b");
testObject.remove("c");
So that I can easily print out the json string of:
{"a":"vala"}
What is the simplest way for me to do this?
org-json-java can do the things you want
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
JSONObject testObject = new JSONObject("{\"a\":\"vala\", \"b\":\"valb\", \"c\":\"valc\"}");
testObject.remove("b");
testObject.remove("c");
System.out.println(testObject.toString()); // This prints out the json string
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The execution result is
{"a":"vala"}
Make sure you've downloaded and imported org.json-YYYYMMDD.jar from here before you run the above code.
Firstly I think you need change title of question.
Secondly, If you want change from String to Json just using org.json library
JSONObject jsonObj = new JSONObject("{\"a\":\"valuea\",\"b\":\"valueb\"}");
Are you tried remove. http://www.json.org/javadoc/org/json/JSONObject.html#remove(java.lang.String)
Json.remove(key)
I am new to java
my string contains : "{'message': 'hello'}";
I want to convert above string to JSON data that gives 'message' key gives 'hello' as value. can any one please help me out ?.
I would use the json.org library, and do something like this:
import org.json.JSONObject;
public class App
{
public static void main( String[] args )
{
String message = "{'message': 'hello'}";
JSONObject json = new JSONObject(message);
System.out.println(json.get("message"));
}
}
I am trying to convert a string to JSONObject object using the below code,but i am getting
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject .
Source:
import net.sf.json.JSONObject;
import org.json.simple.parser.JSONParser;
public static void run(JSONObject jsonObject) {
System.out.println("in run--");
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj;
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
jsonObj = (JSONObject) obj;
run(jsonObj);
}
What is wrong here?
You've imported JSONObject from the wrong package. Change this line:
import net.sf.json.JSONObject;
to this:
import org.json.simple.JSONObject;
Implementing the following solution, You don't even have to bother about a parser...
The Problem here is that u're trying to cast a object of type org.json.simple.JSONObject to net.sf.json.JSONObject. You might wanna try The package org.codehaus.jettison.json.JSONObject. that is enough to do all the required things.
Simple Example:
First, Prepare a String:
String jStr = "{\"name\":\"Fred\",\"Age\":27}";
Now, to parse the String Object, U just have to pass the String to the JSONObject(); constructor method
JSONObject jObj = new JSONObject(jStr);
That should do it and voila! You have a JSONObject.
Now you can play with it as u please.
How So Simple ain't it?
The Modified version of the Code might look like:
import net.sf.json.JSONObject;
import org.codehaus.jettison.json.JSONObject;
public static void run(JSONObject jsonObject) {
System.out.println("in run-- "+jsonObject.getInt("person_id"));
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj = new JSONObject(json);
run(jsonObj);
}
with JSON, It's SssOooooooo simple