This is my C# webservice which generates a JSON String. The below code block is what im using for that.
List<Dictionary<String, Object>> lstdict = new List<Dictionary<String, Object>>();
...
...
...
Logic for connecting db and getting records in msqldat (data reader)
goes here.
...
...
while (msqldat.Read())
{
var detls = new Dictionary<string, object>();
for (int i = 0; i < msqldat.FieldCount; i++)
{
detls.Add(msqldat.GetName(i), msqldat.IsDBNull(i) ? null :
msqldat.GetValue(i));
lstdict.Add(detls);
}
}
JavaScriptSerializer jss = new JavaScriptSerializer();
String mret = jss.Serialize(lstdict);
The above webservice is called in a java code from android studio and it returns the below String.
{"GetDataResult":"[
{\"uname\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"passwd\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"validupto\":\"\\\/Date(1545330600000)\\\/\",
\"dept\":\"juubHSHgLr\/3JWnrZCh5LeeW5Q7lioWOZ1\/Tg+YRy\/o=\",
\"rid\":1},
{\"uname\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"passwd\":\"hkIUZIikXVTC5aNaSva8IQ==\",
\"validupto\":\"\\\/Date(1545330600000)\\\/\",
\"dept\":\"juubHSHgLr\/3JWnrZCh5LeeW5Q7lioWOZ1\/Tg+YRy\/o=\",
\"rid\":2}]"}
I am trying to get the values in android application by using this Java code :
JSONObject uiobj = new JSONObject(mret);
JSONArray arrUserinfo = uiobj.getJSONArray("GetDataResult");
arrUserinfo.getJSONObject(0).getString("uname"))
The code fails at the second line. I'm new to JSON. Not sure if the JSON generated from c# code is not right or java code for parsing is not right. Please advise further. Thank you in advance.
The above json is serialized you need to parse json and then extract the object from it.
See this json valid..
{
"GetDataResult": [{
"uname": "hkIUZIikXVTC5aNaSva8IQ==",
"passwd": "hkIUZIikXVTC5aNaSva8IQ==",
"validupto": "/Date(1545330600000)/",
"dept": "juubHSHgLr/3JWnrZCh5LeeW5Q7lioWOZ1/Tg+YRy/o=",
"rid": 1
},
{
"uname": "hkIUZIikXVTC5aNaSva8IQ==",
"passwd": "hkIUZIikXVTC5aNaSva8IQ==",
"validupto": "/Date(1545330600000)/",
"dept": "juubHSHgLr/3JWnrZCh5LeeW5Q7lioWOZ1/Tg+YRy/o=",
"rid": 2
}
]
}
To parse json in java see below post..
https://www.geeksforgeeks.org/parse-json-java/
Related
I have recently moved to test API's for a new project with Rest Assured. I am not so fluent in Java, so that is why I need to know how to optimise the code.
Let's say I have an API, which output's JSON in this format -
{
"records":[
0: {
"id" : 1232,
"attribute1": "some_value",
"attribute2": "some_value1"
},
1: {
"id" : 1233,
"attribute1": "some_new_value",
"attribute2": "some_new_value1"
}]}
There are around 400 such objects coming inside the records array. I want to get the id of all the 400 records, and store in an array. I am able to do so, but I think the approach can be optimised.
My current code :
private static Response response;
Response r;
JSONParser parser = new JSONParser();
String resp = response.asString();
JSONObject json = (JSONObject) parser.parse(resp);
JSONArray records= ((JSONArray)json.get("records"));
ArrayList<Long> idlist = new ArrayList<Long>();
for(int i=0;i<records.size();i++) {
idlist.add((Long) ((JSONObject)records.get(i)).get("id"));
}
How can I minimize the lines of code to achieve the same thing?
Response response
// Code that assigns the response
List<Long> idList = response.jsonPath().getList("records.id");
// Code that uses the id list.
I'm currently trying to process some JSON but it's given me an error saying that "Index 0 out of range [0..0)" the affected line is the one that is commented out.
JSONObject parentObject3 = new JSONObject(finalJSON3);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
//JSONObject finalObject3 = parentArray3.getJSONObject(0);
tempGameBans = finalObject3.getInt("NumberOfBans");
tempVacBans = finalObject3.getInt("NumberOfMutes");;
Here is my JSON:
{
"players": [
{
"userID": "5648131",
"NumberOfBans": 0,
"NumberOfMutes": 1,
}
]
}
Edit: Currently I am only looking for 1 object per JSON URL so the Index should always be 0, unlike the possible duplicate which seems to be looking for multiple objects.
Edit 2: I found out what the issue is and it's due to the JSON not being correctly sent from my server. Thanks for the help anyway guys.
String jsonString = new String("{\"players\": [{\"userID\": \"5648131\",\"NumberOfBans\": 0,\"NumberOfMutes\": 1}]}");
JSONObject parentObject3 = new JSONObject(jsonString);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
JSONObject finalObject3 = parentArray3.getJSONObject(0);
System.out.println(finalObject3.getInt("userID"));
System.out.println(finalObject3.getInt("NumberOfBans"));
System.out.println(finalObject3.getInt("NumberOfMutes"));
This is working fine, so there has to be some another issue.
You are calling some attribute either not in the JsonObject or the attribute value at that specified index doesn't exist.
Try remove the "," at the end of "NumberOfMutes": 1,.
Because of the project requirement, I have to use com.fasterxml.jackson.databind library to parse JSON data cannot use other JSON libraries available.
I am new to JSON parsing, so not sure if there are better options here?
I would like to know how can I update a string value in an Array node in the JSON file.
Following is a sample JSON. Please note this is not the entire file content, it's a simplified version.
{
"call": "SimpleAnswer",
"environment": "prod",
"question": {
"assertions": [
{
"assertionType": "regex",
"expectedString": "(.*)world cup(.*)"
}
],
"questionVariations": [
{
"questionList": [
"when is the next world cup"
]
}
]
}
}
Following is the code to read JSON into java object.
byte[] jsonData = Files.readAllBytes(Paths.get(PATH_TO_JSON));
JsonNode jsonNodeFromFile = mapper.readValue(jsonData, JsonNode.class);
To update a root level node value e.g. environment in the JSON file , I found following approach on some SO threads.
ObjectNode objectNode = (ObjectNode)jsonNodeFromFile;
objectNode.remove("environment");
objectNode.put("environment", "test");
jsonNodeFromFile = (JsonNode)objectNode;
FileWriter file = new FileWriter(PATH_TO_JSON);
file.write(jsonNodeFromFile.toString());
file.flush();
file.close();
QUESTION 1: Is this the only way to update a value in JSON file and is it the best way possible? I'm concerned on double casting and file I/O here.
QUESTION 2: I could not find a way to update the value for a nested Array node e.g. questionList. Update the question from when is the next world cup to when is the next soccer world cup
You can use ObjectMapper to parse that JSON, it is very easy to parse and update JSON using pojo class.
use link to convert your json to java class, just paste your json here n download class structure.
You can access or update nested json field by using . (dot) operator
ObjectMapper mapper = new ObjectMapper();
String jsonString="{\"call\":\"SimpleAnswer\",\"environment\":\"prod\",\"question\":{\"assertions\":[{\"assertionType\":\"regex\",\"expectedString\":\"(.*)world cup(.*)\"}],\"questionVariations\":[{\"questionList\":[\"when is the next world cup\"]}]}}";
TestClass sc=mapper.readValue(jsonString,TestClass.class);
// to update environment
sc.setEnvironment("new Environment");
System.out.println(sc);
//to update assertionType
Question que=sc.getQuestion();
List assertions=que.getAssertions();
for (int i = 0; i < assertions.size(); i++) {
Assertion ass= (Assertion) assertions.get(i);
ass.setAssertionType("New Type");
}
I am new to using the json-simple library in Java and I've been through both the encoding and decoding samples. Duplicating the encoding examples was fine, but I have not been able to get the decoding ones to work with mixed type JSON.
One of my problems is that there are too many classes in the library which are not properly documented, and for which I do not have the source (in order to be able to read through and understand their purpose). Consequently, I am struggling to understand how to use a lot of these classes.
After reading this example:
String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
public List creatArrayContainer() {
return new LinkedList();
}
public Map createObjectContainer() {
return new LinkedHashMap();
}
};
try {
Map json = (Map)parser.parse(jsonText, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
System.out.println("==toJSONString()==");
System.out.println(JSONValue.toJSONString(json));
} catch(ParseException pe) {
System.out.println(pe);
}
from the json-simple official decoding tutorial, I tried to decode this JSON:
{
"stat":{
"sdr": "MAC address of FLYPORT",
"rcv": "ff:ff:ff:ff:ff:ff",
"time": "0000000000000",
"type": 0,
"subt": 0,
"argv": [
{"type": "6","val": "NetbiosName"},
{"type": "6","val": "MACaddrFlyport"},
{"type": "6","val": "FlyportModel"},
{"type": "1","val": id}
]
}
}
I am writing following code to decode:
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{1,2},{2,3}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON);
But it doesn't work. Infact I was not able to get the unmodified example working either, and the original authors have not explained their code.
What is the easiest way to decode this JSON as shown?
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
Well your jsonString is wrong.
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";
use this jsonString and if you use the same JSONParser and ContainerFactory in the example you will see that it will be encoded/decoded.
Additionally if you want to print your string after stat here it goes:
try{
Map json = (Map)parser.parse(jsonString, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
Object entry = json.get("stat");
System.out.println(entry);
}
And about the json libraries, there are a lot of them. Better you check this.
Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.
To add the jar file to your project in Eclipse, do the following:
Right click on your project, click Build Path > Configure Build Path
Goto Libraries tab > Add External JARs
Locate the JAR file and add
This is the JSON String we want to decode :
{
"stats": {
"sdr": "aa:bb:cc:dd:ee:ff",
"rcv": "aa:bb:cc:dd:ee:ff",
"time": "UTC in millis",
"type": 1,
"subt": 1,
"argv": [
{"1": 2},
{"2": 3}
]}
}
I store this string under the variable name "sJSON"
Now, this is how to decode it :)
// Creating a JSONObject from a String
JSONObject nodeRoot = new JSONObject(sJSON);
// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");
// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");
I'm trying to parse this string into java, but I keep getting errors.
{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}
When I use this code ...
String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");
I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?
The array named "sources" is several levels deep. You need to traverse down into the json.
Code formatters help with this stuff...
http://jsonformatter.curiousconcept.com/
{
"id":1,
"jsonrpc":"2.0",
"result":{
"limits":{
"end":3,
"start":0,
"total":3
},
"sources":[
{
"file":"/media/storage/media/re Music/",
"label":"re Music"
},
{
"file":"/media/storage/media/ra Music/",
"label":"ra Music"
},
{
"file":"addons://sources/audio/",
"label":"Music Add-ons"
}
]
}
}
It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:
JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");
Your json should have top level object, from there you need to get child objects. See this link for more detail.