When I am building a json object from string it is appended with a root key "nameValuePairs".
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
results to
{"nameValuePairs":{"b":"{}","c":"{}","a":"{}"}}
Why?
Any way to prevent that?
Btw, I am using the string json to represent the actual json which I will use later.
First of all your json is syntactically correct but I guess you wished to represent objects as values, in your case the curly brackets are evaluated as simple strings:
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
using a json like this instead will produce values as objects:
String curStr = "{\"e\": {}, \"f\": {}, \"g\": {}}";
JSONObject oldObj = new JSONObject(curStr);
Anyway, I've tried to create that JSONObject and then print a toString of it, and it will simply print the json, without any accessory name.
As you find out in the comment the problem was given by Gson, that will evaluate the JSONObject as a map. I've tried a little example and I've got "map" as field. Probably I've tried a different version of Gson.
Gson gson = new Gson();
String jsonStr = gson.toJson(oldObj);
result: {"map":{"f":"{}","g":"{}","e":"{}"}}
If you want to create a custom object and deserialize a json with Gson create a class with those properties and use the fromJson(String json, Class clazz) method
public class Test {
private String e;
private String f;
private String g;
}
and
Gson gson = new Gson();
Test myTestObj = gson.fromJson(curStr, Test.class);
Hope this will help you. :)
You can try jsonStringer instead.
Something like below code:
JSONStringer jObject = new JSONStringer()
.object()
.key("UserName").value(userNameValue)
.key("Name").value(nameValue)
.key("EmailId").value(emailIdValue)
.key("CountryId").value(contryIdValue)
.key("CountryName").value("") // It should be blank As Spanish Name is not set if User have App in Spanish
.key("State").value(stateValue)
.key("City").value(cityValue)
.key("ImageByteArray").value(imageBytes)
.endObject();
UPDATE
I have just use your code in my App and check it.
Its showing me the result as we have formed.
Result i am getting is:
{
"f": "{}",
"g": "{}",
"e": "{}"
}
Please check your packages you are importing.
For your reference i am importing below class to represent json object.
import org.json.JSONException;
import org.json.JSONObject;
Just import above class and see the result.
Let me know if you still have any query.
Related
All examples of converting string to json are of javascript. mine is java class. So, i have a simple java string but formated in json. now i have recieved that from jquery post. now i have to convert that string into json object so that i can access the specific fields.
controller class
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public void storeData(#RequestParam(value = "temp_str", required = false) String j_str, HttpServletRequest request) {
// do the conversion and extraction of data from "j_str"
}
j_str variable is recieveing this string
{"temp_data":[{"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}]}
http://www.javacreed.com/simple-gson-example/
Gson gson = new GsonBuilder().create();
Person p = gson.fromJson("your json string", Person.class);
System.out.println(p);
you can use that libary to manage json objectos its very cool
the Person.class is a java bean must have all properties you have in your string
If your Json string is extremely simple, you can just use:
JSONObject jobj=new JSONObject(j_str);
Now you can access the JSON elements by:
JSONArray jarr=jobj.getJSONArray('temp_data');
JSONObject jarr1=jarr.get(0); // will contain {"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}
Now you can further access jarr1 similar to jobj.
I have below JSON response in which I need to check whether response field has null value or not. If response field has null value then I need to exit out of the program.
[
{
"results": {
"response": null,
"type": "ABC"
},
"error": null
}
]
What is the easiest way to check this out? One option I know is to convert JSON to POJO and then check response field. Is there any other way?
If you are using codehouse's JSON library , you could do something like this:
JSONObject jsonObj = new JSONObject(jsonString);
System.out.println(jsonObj .isNull("error") ? " error is null ":" error is not null" );
if using Google's gson :
JsonObject jsonObject = new JsonParser().parse(st).getAsJsonObject();
JsonElement el = jsonObject.get("error");
if (el != null && !el.isJsonNull()){
System.out.println (" not null");
}else{
System.out.println (" is null");
}
I am using org.json.JSONObject. This is an example that you can use to test a JSONObject is null or not.
package general;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class CheckNullInJSONObject {
public static void main(String[] args) {
JSONObject json = new JSONObject("{results : [{response:null}, {type:ABC}], error:null}");
JSONArray array = json.getJSONArray("results");
try {
for(int i = 0 ; i < array.length() ; i++){
JSONObject response = array.getJSONObject(i);
if (response.isNull("response")){
throw new Exception("Null value found");
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
Regex/parse string to get the response field value or use google gson lib: https://github.com/google/gson to create object and access any field.
The safest way to reliably check the value of the response field for null is (as you suggested) to model the json data structure with POJO classes and use a json library such as Gson or Jackson to deserialize your json to your POJOs.
Don't listen to other answers here advising the use of regex. Building a correct and reliable json parser using only regex is a) bug prone and b) can have poor performance.
Two ways depending on your needs:
Quick and dirty way which might actually be useful/good enough/good performance:
String jsonString = ...
jsonString.contains("\"response\": null");
Yes, it's error prone if the server changes anything, even line breaks etc. But it will be using a lot less resources.
Variations with higher tolerance include regexp that simply allow zero or multiple whitespace between field name and value. Another variant is to find the index of the field and look for the value after that manually:
int fieldIndex = jsonString.indexOf("\"response\":");
//left as an exercise...
Json parsing with a library, such as Gson (Google's json library):
Simple minimum Results class:
public static class Result {
public static class Results {
public String response;
}
public Results results;
}
Parse and check (ignoring null and length check of array):
Gson gson = new Gson();
Result[] results = gson.fromJson(jsonString, Result[].class);
System.out.println(results[0].results.response);
Gson can be found here:
https://github.com/google/gson
I need to blur the user id present in my original json string with another user id. After that I will construct a new json string with everything same but the only difference will be the user id is different.
As an example, if my original json string is like this -
{
"user_id":{"long":1234},
"client_id":{"int":0},
"affinity":[
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
Then my new json string will be - The only difference is I have a new user id in it and apart from that everything is same.
{
"user_id":{"long":98765},
"client_id":{"int":0},
"affinity": [
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
The only problem I have is, I won't have json string in the above format only so I cannot use POJO to serialize my json string since my json string will have different formats but user_id field will always be like that in all my json string and it will be long as well. The other fields might be different depending on the json string I have.
I am using Gson to do this. I have got the below method but not sure how can I construct a new json with newUserId in it and everything should be same?
private static String creatNewJson(String originalJsonResponse, long newUserId) {
JsonElement jelement = new JsonParser().parse(originalJsonResponse);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("user_id");
// not sure what I should do here to construct a new json with newUserId
}
Or Gson is not the right way to do this? Should I be usingg regular expressions for this?
How about input.replaceAll("(\"user_id\":\\{\"long\":)\\d+", "$1" + newID)?
I've recently decided to rewrite one of my older android applications and I can't figure out how to convert server response like this:
{
"response": "SUCCESS",
"data": {
"0": {
... fields ...
},
"1": {
... fields ...
},
... another objects
}
}
to regular java object (or in this case list of objects). I was previously using this method:
JSONObject response = new JSONObject(stringResponse);
JSONObject dataList = response.getJSONObject("data");
int i = 0;
while (true) {
dataList.getJSONObject(String.valueOf(i)); // here I get wanted object
i++;
}
to get relevant objects and then I can put them into List, but now I'm using Retrofit library and I'm not able to find any clean solution to parse such weird object using gson and retrofit.
Thanks for any help.
Edit: What I want:
Send request using retrofit like this:
#GET("/some params")
void restCall(... another params..., Callback<Response> callback);
and then have List of objects in Response object. What I don't know is how to declare Response object, so it can convert that weird response into normal List of objects.
You have many libraries around for this.. One i used was json-simple There you can just use:
JSONValue.parse(String);
look into gson too! i'm using it for all my projects, serializing and deserializing to pojos is remarkably simple and customizable (if needed, most things are fine out of the box)
gson
here is their first example:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
obj = gson.fromJson( json );
==> you get back the same object
I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need