logo
down
shadow

JSON String to List of objects


JSON String to List of objects

By : user2951710
Date : November 18 2020, 03:49 PM
I wish this helpful for you Your JSON matches an object (see HotelPromotionList below), not a list.
code :
class HotelPromotionList {
   List<HotelPromotion> hotelPromotions;
}

class HotelPromotion {
   int id;
   int version;
   String description;
   String status; // might be an enum
   // ...
}


Share : facebook icon twitter icon
How to use a case class to deserialize an array of json objects to List[Map[String,String]]

How to use a case class to deserialize an array of json objects to List[Map[String,String]]


By : user6647972
Date : March 29 2020, 07:55 AM
To fix the issue you can do As I replied to you on the Salat mailing list, Salat doesn't support deserializing nested collections right now.
https://github.com/salat/salat/wiki/Collections
How to convert JSON to list string, when some of the JSON objects are string and some are array?

How to convert JSON to list string, when some of the JSON objects are string and some are array?


By : Suman Pandey
Date : March 29 2020, 07:55 AM
it fixes the issue You have a lot of problems going on here. Let me start with the reason you are getting this error: your JSON contains a single outer object, but you are trying to deserialize it into a list. This won't work. If there's just a single object in the JSON, you need to deserialize into a single object.
Second issue, the data for your StaffDetail class is not at the top level of your JSON; it is one level down-- in the value of the d property of the outer JSON object. To fix this, you need to introduce a wrapper class and deserialize into that. Then you can retrieve the StaffDetail from the wrapper.
code :
class Wrapper
{
    public StaffDetail d { get; set; }
}
class StaffDetail
{
    public string __type { get; set; }
    public string SessionID { get; set; }
    public string Code { get; set; }
    public string Message { get; set; }
    public object Rows { get; set; }

    [JsonConverter(typeof(ColumnsConverter))]
    public List<string> Columns { get; set; }

    [JsonConverter(typeof(SetConverter))]
    public List<string> Set { get; set; }
}
class ColumnsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // this converter can handle converting some JSON to a List<string>
        return objectType == typeof(List<string>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Convert an object to a flat list of strings containing
        // just the property names from the object.
        JObject obj = JObject.Load(reader);
        return obj.Properties().Select(p => p.Name).ToList();
    }

    public override bool CanWrite 
    { 
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
class SetConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // this converter can handle converting some JSON to a List<string>
        return objectType == typeof(List<string>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Convert an array of arrays of strings to a flat list of strings
        JArray array = JArray.Load(reader);
        return array.Children<JArray>()
            .SelectMany(ja => ja.Children(), (ja, jt) => jt.Value<string>()).ToList();
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
StaffDetail detail = JsonConvert.DeserializeObject<Wrapper>(json).d;
class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""d"": {
                ""__type"": ""CubeJsonData"",
                ""SessionID"": null,
                ""Code"": 0,
                ""Message"": """",
                ""Rows"": {},
                ""Columns"": {
                    ""Place 1"": [
                        0,
                        1
                    ],
                    ""Place 2"": [
                        0,
                        2,
                        4,
                        6
                    ]
                },
                ""Set"": [
                    [
                        ""Number 1""
                    ],
                    [
                        ""Number 2""
                    ],
                    [
                        ""Number 3""
                    ]
                ]
            }
        }";

        StaffDetail detail = JsonConvert.DeserializeObject<Wrapper>(json).d;

        Console.WriteLine("Columns: " + string.Join(", ", detail.Columns));
        Console.WriteLine("Set: " + string.Join(", ", detail.Set));
    }
}
Columns: Place 1, Place 2
Set: Number 1, Number 2, Number 3
Convert String of Json object lists to list of JSON objects

Convert String of Json object lists to list of JSON objects


By : Bikram Tamang
Date : March 29 2020, 07:55 AM
around this issue After making a HTTP get request i'm returned with a list of JSON objects, is there any way in which I can convert this String into a list of JSON objects?? , Simple json api can do what you want for e.g
code :
String stringToParse  = "[{'name':'test','description':'','dbType':'sql'}, "
            + "{'name':'test1','description':'','dbType':'sql server'},"
            + "{'name':'test2','description':'','dbType':'sql oracle'}]";


JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(stringToParse);
How to get list of objects from json string c# Newtonsoft.json

How to get list of objects from json string c# Newtonsoft.json


By : rory
Date : March 29 2020, 07:55 AM
hope this fix your issue The JSON string you get is not a list, but an object which has a list on a nested level. You will have to deserialize the outermost structure and then get the respective nested property.
You can either define a whole class representing the complete structure of your data, or, if you are only interested in the List of Houses, just use JObjects
code :
var o = JsonConvert.DeserializeObject<JObject>(json);
var h = o.Value<JObject>("Data")
    .Value<JArray>("Houses")
    .ToObject<List<Houses>>();
Jackson - Java Objects with List<Map<String,String>> to Json String conversion

Jackson - Java Objects with List<Map<String,String>> to Json String conversion


By : user3568682
Date : March 29 2020, 07:55 AM
it fixes the issue In cases like this where default representation of POJO is not what you want you need to implement custom serialisers. In your case they could look like below:
code :
class ResourceJsonSerializer extends JsonSerializer<Resource> {
    @Override
    public void serialize(Resource value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeFieldName(value.getName());
        gen.writeObject(value.getItems());
        gen.writeEndObject();
    }
}

class ItemJsonSerializer extends JsonSerializer<Item> {

    @Override
    public void serialize(Item value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        writeMap(value.getSystemFields(), gen);
        writeMap(value.getDataFields(), gen);
        gen.writeEndObject();
    }

    private void writeMap(Map<String, String> map, JsonGenerator gen) throws IOException {
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                gen.writeStringField(entry.getKey(), entry.getValue());
            }
        }
    }
}
@JsonSerialize(using = ResourceJsonSerializer.class)
class Resource {
@JsonSerialize(using = ItemJsonSerializer.class)
class Item {
Related Posts Related Posts :
  • Forcefully terminating a thread I didn't write in Java
  • Issue with ojdbc jar in Maven
  • String array length java
  • Java basic compilation error
  • Inquiry about writing a Char via ByteBuffer
  • Getting unexpected results when type casting between long and double
  • Variable throws variable might not have been initialized error
  • Start/stop java application from an external script
  • Confusion in declaring String Objects
  • What are some ways to do multi-core programming on Android, not just multi-thread?
  • hibernate - process scoped identity
  • Null Pointer Exception on getGraphics()
  • Can we print a java message on console without using main method, static variable and static method?
  • sending text from editText to ListView (2 activities)
  • Transfer value from JList to another class in Java
  • Creating 2 streams with one socket
  • How measure time stolen from virtual machine, in Scala/Java?
  • How can I programmatically generate keypress events?
  • org.apache.commons.net.ssh documentation
  • Implementation of Dijkstra`s Algorithm - Stuck in an infinite loop
  • Should I throw IllegalArgmentException when 'user of given id not exist'?
  • In Nimbus, how to paint TextField when MouseOver?
  • why won't checkforWin(File f) return true when it is true?
  • Android: Cursor is always returning null even if the database is not empty
  • Repeating for loop in menu
  • Can Java garbage collector randomly delete objects in the On-Heap tier?
  • Apache CXF Exception: SSL connection unexpectedly closed
  • Add properties to ArrayList<Object> in Java
  • Multiple Adapters or One Adapter for different lists and objects - Code Performance
  • Is it good practice in Java for a class's method to redundantly return a modified global field of the class?
  • How to change the color of the background in libgdx labels?
  • direct file path not working
  • ClassFileTransformer + Javassist: no such field
  • How do I change and instance variable for an object which the user selects from a combobox?
  • reading and updating a large xml file in java
  • ActionListener and Thread.sleep
  • What is the maximum of number of arguments for varargs in java?
  • When I compile I get an error as "ask" cannot be resolved or is not a field"
  • What is the best way to check if 4 integer variables are equal to 0?
  • Storing constant webdriver elements in an enum
  • Java: Why main class does not extend Thread class
  • Java - how to find out if a directory is being used by another process?
  • How can I get a method to print?
  • Java unknown exceptions
  • BufferedReader,StreamWriter crash
  • found raw type: JComboBox
  • Java Generics -> Function return type
  • how to refresh contents of jtable on event of action listener?
  • Why does List interface extend Collection interface?
  • Pros and Cons of Clojure http client libraries
  • use final inside a for each loop
  • Convert java data object to service object
  • Unsupported major.minor version 51.0 while executing JSP
  • How do I display a word diagonally in Java?
  • making sure one task completes before another starts in java
  • My program gives an index out of bounds error
  • Removing duplicate characters in a String (user inputted keyword)
  • Jersey 2.0 Content-Length not set
  • AWS.SimpleQueueService.NonExistentQueue Exception thrown when Accessing Existing SQS queue
  • Where can I find the source code for the com.sun.jdi package?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org