How to Create JSON Object Using String

How to convert jsonString to JSONObject in Java

Using org.json library:

try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}

How to create JSON Object using String?

org.json.JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

Create JSONObject from string

Just change the way you create your JSONObject.

JSONObject jObject = new JSONObject(jsonStr);
//later you can access to your array
JSONArray tasks=(JSONArray) jObject.get("tasks");

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

Converting string to json object using json.simple

Try this:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

Create JSON object from string in C#

In the most recent version of .NET we have the System.Text.Json namespace, making third party libraries unecessary to deal with json.

using System.Text.Json;

And use the JsonSerializer class to serialize:

var data = GetData();
var json = JsonSerializer.Serialize(data);

and deserialize:

public class Person
{
public string Name { get; set; }
}

...
var person = JsonSerializer.Deserialize<Person>("{\"Name\": \"John\"}");

Other versions of .NET platform there are different ways like the JavaScriptSerializer where the simplest way to do this is using anonymous types, for sample:

string json = new JavaScriptSerializer().Serialize(new
{
message = new { text = "test sms" },
endpoints = new [] {"dsdsd", "abc", "123"}
});

Alternatively, you can define a class to hold these values and serialize an object of this class into a json string. For sample, define the classes:

public class SmsDto
{
public MessageDto message { get; set; }

public List<string> endpoints { get; set; }
}

public class MessageDto
{
public string text { get; set; }
}

And use it:

var sms = new SmsDto()
{
message = new MessageDto() { text = "test sms" } ,
endpoints = new List<string>() { "dsdsd", "abc", "123" }
}

string json = new JavaScriptSerializer().Serialize(sms);


Related Topics



Leave a reply



Submit