I've below json value in my StringBuilder variable, I want to parse all id key value and store it again in StringBuilder.
{"status":"success","id":"1"}
{"status":"success","id":"2"}
{"status":"success","id":"3"}
{"status":"success","id":"4"}
{"status":"success","id":"5"}
{"status":"success","id":"6"}
Expected output:
1
2
3
4
5
6
How can I parse these value in java?
I tried below option but it doesn't help:
StringBuilder str = new StringBuilder();
str.append(jsonStringValue);
JSONObject jObj = new JSONObject(str);
jObj.getString("id");
Using JSONTokener
JSONTokener t = new JSONTokener(str.toString());
while (t.more()) {
JSONObject o2 = (JSONObject) t.nextValue();
System.out.println(o2.getString("id"));
}
But I'm getting below error message:
org.json.JSONException: Missing value at character 128
If you're using org.json, You can use JSONTokener.
Here's example shows how it works.
public static void main(String args[]) throws JSONException {
String str1 = "{\"strValue\":\"string\"}\n{\"intValue\":1}";
JSONTokener t = new JSONTokener(str1);
JSONObject o1 = (JSONObject) t.nextValue();
JSONObject o2 = (JSONObject) t.nextValue();
System.out.println(o1.getString("strValue"));
System.out.println(o2.getLong("intValue"));
System.out.println(t.more()); // Check if there's more token. can be used to process with loop.
}
Or if you can change input string, you can put those object into Json array.
[
{"status":"success","id":"1"},
{"status":"success","id":"2"},
{"status":"success","id":"3"},
{"status":"success","id":"4"},
{"status":"success","id":"5"},
{"status":"success","id":"6"}
]
In that case you can use org.json.JSONArray to handle it.
You can use regexps like this
public class Test {
public static void main(String[] args) {
StringBuilder inputBuf = prepareStringBuilder();
StringBuilder outputBuf = new StringBuilder();
Pattern pattern = Pattern.compile(":\"(\\d+)\"");
Matcher matcher = pattern.matcher(inputBuf);
while (matcher.find()) {
String group = matcher.group(1);
outputBuf.append(group);
}
System.out.println(outputBuf);
}
private static StringBuilder prepareStringBuilder() {
StringBuilder buf = new StringBuilder();
buf.append("{\"status\":\"success\",\"id\":\"1\"}");
buf.append("{\"status\":\"success\",\"id\":\"2\"}");
buf.append("{\"status\":\"success\",\"id\":\"3\"}");
buf.append("{\"status\":\"success\",\"id\":\"4\"}");
buf.append("{\"status\":\"success\",\"id\":\"5\"}");
buf.append("{\"status\":\"success\",\"id\":\"6\"}");
return buf;
}
}
Related
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
I'm studying Spring Framework and I'm parsing JSON data but it shows:
Unexpected token LEFT BRACE({) at position 4.
However eclipse did not show any indication of an error.
Here is my controller source:
#RequestMapping(value = "/listcall.do", method = RequestMethod.GET)
public void home( #RequestParam("val") String id, HttpServletRequest request , HttpServletResponse response) throws JsonIOException, IOException, ParseException {
response.setCharacterEncoding("utf8");
response.setContentType("application/json");
String valuewhat = id ;
JsonArray jarraySend = new JsonArray();
//System.out.println(request.getParameter("val"));
JSONParser parse = new JSONParser();
FileReader fileReader = new FileReader("D:\\Spring\\sworkspace\\Calendar\\src\\main\\resources\\somelist.json");
Scanner sc = new Scanner(fileReader);
String inline = null;
while(sc.hasNext())
{
inline+=sc.nextLine();
}
JSONObject json = (JSONObject) parse.parse(inline);
JSONArray jarray_1 = (JSONArray) json.get("listing_property_type_information");
for(int i=0;i<jarray_1.size();i++) {
JSONObject jsonobj_1 = (JSONObject)jarray_1.get(i);
//JsonArray jsonarr_2 = (JsonArray) jsonobj_1.get("property_type_groups");
jarray_1 = (JSONArray) jsonobj_1.get("property_type_groups");
for(int j=0;j<jarray_1.size();j++) {
JSONObject jsonobj_2 = (JSONObject) jarray_1.get(j);
//something do.....
}
}
//jarray.add(json);
new Gson().toJson(jarray_1, response.getWriter());
}
I've been practicing to mimic functions like the AirBNB site.
JSON file is located at:
https://www.airbnb.co.kr/become-a-host/room <-Here is a scrolling copy
You should have a look at your inline variable.And you should declare this variable like thisString inline = ""; rather than String inline = null; which will make the string you spliced start with "null"
This means your json is bad. Eclipse cannot catch it because it is a runtime error.
public static String fetchFromJSONNext() throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
// String filename=System.getProperty("user.dir")+"\\src\\com\\test\\mtcn1.json";
String filename=System.getProperty("user.dir")+"\\src\\com\\test\\mtcn1.json";
//System.out.println(request.getParameter("val"));
JSONParser parse = new JSONParser();
FileReader fileReader = new FileReader(filename);
Scanner sc = new Scanner(fileReader);
String inline ="";
String sj ="";
while(sc.hasNext()){
inline+=sc.nextLine();
JSONObject jsonobj_2 = (JSONObject) parse.parse(inline);
//something do.....
Object g=jsonobj_2.get("result");
JSONObject h = (JSONObject) g;
sj=(String) h.get("wutaf_rpcmsg");
}
return sj;
}
So far with the code I have, I am able to get results as a JsonObject. However, I am trying to get the coordinates of the location based on the postal code that I have entered. How can I retrieve the "lat" and "lng" as Strings/JsonElements? Would really appreciate if you can give me some insight. Thanks!
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
//the JSON builder
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String restaurant = request.getParameter("r");
String customer = request.getParameter("c");
//Get coordinates of the restaurant
String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
URL url = new URL(longLatApi);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", longLatApi);
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
out.println(gson.toJson(obj));
JsonElement and its subclasses have nice methods to iterate through JSON elements of different kinds: null, a primitive (numbers, string literals, and booleans), a JSON object, or a JSON array. Knowing an exact structure of the response JSON document, you can extract child elements pretty straight-forward:
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
final JsonParser jsonParser = new JsonParser();
// Extract the `results` array
final JsonArray resultsJsonArray = jsonParser.parse(reader)
.getAsJsonObject()
.get("results")
.getAsJsonArray();
// Iterate over each result array element
for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
// Picking up the `geometry` property as a JSON object
final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
// And dumping the location
final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
dumpLocationJsonObject("Location", locationJsonObject);
final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
// There can be a `bounds` object with two additional properties
if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
}
}
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}
The output:
Greenwich, London SE10, UK
Location: (51.48257659999999; -0.0076589)
As an alternative approach, you can define custom JSON to Java classes mappings in order to deserialize the JSON document as a custom class instance, and not just JsonElement (something like gson.fromJson(reader, customType)). Both approaches have pros and cons.
I am getting this from server
"[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]"
The above text is not an array, but a string returned from server.
I want to convert this in an ArrayList
Is there a way to convert it?
There is no good idea to manually parse that string. You should use a library that parses JSON strings for you. Anyhow the given string is not a valid JSON string and like others have mentioned you should request JSON formatted data from the server.
If your server only returns like this and you need to manually parse then this would be a solution. Not a very good one, but it does the job.
public static void main(String[] args) {
List<String> words = new ArrayList<>();
String string = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
String withoutBrackets = string.replaceAll("[\\[\\](){}]", ""); // Remove all the brackets
for (String word : withoutBrackets.split(",")) {
String singleWord = word.replaceAll("\"", "");
words.add(singleWord);
}
System.out.println(words);
}
Can be done using separator, where s is String:
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Try using Gson. Add this to your gradle
compile 'com.google.code.gson:gson:2.2.4'
Hope this helps -
String str = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
Gson gson=new Gson();
ArrayList<String> strings = gson.fromJson(str,new TypeToken<ArrayList<String>>(){}.getType());
This will work
String text = [\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
text = text.replaceAll("[\\[\\](){}\"]", "");
List<String> list = Arrays.asList(text.split(","));
Modify your String using
str = str.replace ("[", "").replace ("]", "");
so it is the same as
String str = "\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"";
then use
List<String> al = new ArrayList<String>(Arrays.asList(str.split(",")));
System.out.println(al);
This is the correct way to parse JSON String to ArrayList :)
ArrayList<String> list = new ArrayList<String>();
String newArrayy ="[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
imagePath = newArrayy;
try {
JSONArray jsonArray = new JSONArray(imagePath);
if (null != jsonArray) {
Logger.LogError("imagePathhh", jsonArray.toString() + "" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
String value =(String) jsonArray.getString(i);
list.add(value); dataBaseCurdOperation.insertPaymentPath(jsonArray.getString(i));
}
} else {
}
} catch (Exception e) {
}
}
Sanjay in his answer pointed it out correct , that it is not correct format.
Still if you are using Gson library to parse JSON data, then the following method take care of this format also. So you have no need to do anything :)
new Gson().fromJson(your_server_response, Model.class);
One more way to do this is using java's inbuilt method
public String replaceAll (String regularExpression, String replacement)
I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}