My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);
Related
I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.
This is the JSON file I am working with
{"sentiment":
{"document":
{
"label": "positive",
"score": 0.53777
}
}
}
I need to access the value in label and score. using java. How can I do that?
Find below the code I am using right now:
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = new JSONObject();
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
System.out.println(test);
} catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
Why is it printing the value as null.
You might want to have a look at JacksonXml for json parsing.
Right now the problem is that you're not using the JsonObject returned by parser.parse(...).
Instead you use the get method on objects you just created. This of course means that you don't getthe valie you want to.
Try to use following code (JSONObject jsonObject = (JSONObject) object instead of JSONObject jsonObject = new JSONObject();), because you didn't use object at all, just create new empty JSONObject.
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
JSONObject documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
System.out.println(label);
float score = (float) documentobject.get("score");
System.out.println(score );
}catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
You have to make use of object created in Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); while creating the jsonObject
For that you can look at the code below:
Object object = parser
.parse(new FileReader("file2.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
You will get the positive printed on console.
you should see the content in para 'sentimentobject',force convert into class JSONObject can not get the value you want.
I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). These POJOs are often called Data Transfer Objects (DTOs) and give you a way to turn your JSON fields into properly typed members of the corresponding DTO.
Here is an example method to do that. The ObjectMapper(s) are generally maintained as statics somewhere else because FasterXML's implementation caches information to improve efficiency of object mapping operations.
static final ObjectMapper mapper = new ObjectMapper();
This is the JSON deserialization method:
public static <T> T deserializeJSON(
final ObjectMapper mapper, final InputStream json,
final Class<T> clazz)
throws JsonParseException, UnrecognizedPropertyException,
JsonMappingException, IOException
{
final String sourceMethod = "deserializeJSON";
logger.entering(sourceClass, sourceMethod);
/*
* Use Jackson support to map the JSON into a POJO for us to process.
*/
T pojoClazz;
pojoClazz = mapper.readValue(json, clazz);
logger.exiting(sourceClass, sourceMethod);
return pojoClazz;
}
Assuming I have a class called FooDTO, which has the appropriate Jackson annotations/getters/setters (note you must always provide a default empty public constructor), you can do this:
FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);
The deserialization throws a few different exceptions (all of which have IOException as their parent class) that you will need to handle or throw back to the caller.
Here besides of the correction alreay addressed in comments and other answers, I include some other changes you can benefit of:
It is not necessary to initialize the JSONObjects with a new instance that is going to be ovewritten in the next line.
You can use getJSONObject(), getString(), getFloat() instead of get(), in this way you don't need to cast the result.
public void parseJson() {
JSONParser parser = new JSONParser();
try
{
JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
JSONObject sentimentobject= null;
JSONObject documentobject = null;
sentimentobject= jsonObject.getJSONObject("sentiment");
documentobject= sentimentobject.getJSONObject("document");
String label = documentobject.getString("label");
float score = documentobject.getFloat("score");
String output = String.format("Label: %s Score: %f", label, score);
System.out.println(output);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
Also for this kind of objects, where the attribute names could act as object properties, I suggest you take a look at Gson library. After modeling the json as a composition of POJOs, the parsing takes 1 line of code.
I'm using Google Play Games Snapshot and I have to pass in the data I need to save by using JSON.
Here is the JSON file:
{"Date":1531043635316,"Daily bonus":2,"sound enabled":true,"total coins":2099300,"high score":0,"Btns Set":1,"leftBtnX":46,"leftBtnY":18,"leftBtnsize":1,"upBtnX":105,"upBtnY":18,"upBtnsize":1,"rightBtnX":164,"rightBtnY":18,"rightBtnsize":1,"guardBtnX":288,"guardBtnY":18,"guardBtnsize":1,"chargeBtnX":363,"chargeBtnY":18,"chargeBtnsize":1,"attackBtnX":438,"attackBtnY":18,"attackBtnsize":1,"superBtnX":438,"superBtnY":58,"superBtnsize":1,"ultimateBtnX":363,"ultimateBtnY":58,"ultimateBtnsize":1,"dpadX":80,"dpadY":40,"dpadSize":1,"gpadX":405,"gpadY":59,"gpadSize":1}
Now when I try to change only one of them using this code:
private byte[] saveToJSON(){
try {
JSONObject obj = new JSONObject();
obj.put("total coins", Settings.totalCoins);
return obj.toString().getBytes();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("Error converting save data to JSON.", e);
}
}
The entire file get's changed to only this single parameter, it becomes this:
{"total coins":2099300}
Now how Can I just modify a single parameter value?
Sorry, this is the first time for me to work with JSON
JSONObject obj = new JSONObject(); make you create a new json object,that's the reason,you can change to below code:
String jsonStr = "";//your json string
JSONObject obj = new JSONObject(jsonStr);
obj.put("total coins", Settings.totalCoins);
I have an android app and a Web Service. When I want to edit some register I have to get the whole record from the database and put every field in a Edit Text.
The Web Service return me this to the android app
[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]
And I have a variable called "result" that have this JSON string
How do I put every field in a independent edit text in my Android App?
something like:
txtid.setText(result[0]);
txtType.setText(result[1]);
txtDate.setText(result[2]);
txtLocation.setText(result[3]);
txtPerson.setText(result[4]);
where "result" is my JSON string.
try below code.
if you have more than one json object in array
String response = "[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]"
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
}
} catch (JSONException e) {
e.printStackTrace();
}
And if you have only one object in array then no need to use for loop use directly this way
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
} catch (JSONException e) {
e.printStackTrace();
}
there is a library to convert Json object to android model that call GSON
at first create a model with your input object like below:
class InputModel {
String id;
String 0; //it's better to change this object name
String tipo;
...
}
next, you can use Gson to bind your input to your model. it should be something like this:
InputModel mInput = new Gson().fromJson(data);
ps1: data is your input string
ps2: if you want the name of your input be different with your input name, you can use an annotation like this:
#SerializedName("id")
String productId;